Merge branch 'msbuilddll2'
authorAtsushi Eno <atsushieno@gmail.com>
Fri, 24 Jan 2014 07:41:00 +0000 (16:41 +0900)
committerAtsushi Eno <atsushieno@gmail.com>
Fri, 24 Jan 2014 07:41:00 +0000 (16:41 +0900)
454 files changed:
Makefile.am
configure.in
data/Makefile.am
data/config.in
data/xbuild12.pc [new file with mode: 0644]
eglib/src/gpath.c
man/mono.1
mcs/Makefile
mcs/build/Makefile
mcs/build/profiles/monodroid.make
mcs/build/profiles/monotouch_runtime.make
mcs/build/profiles/net_2_0.make
mcs/build/profiles/net_3_5.make
mcs/build/profiles/net_4_0.make
mcs/build/profiles/net_4_5.make
mcs/build/profiles/xammac.make [new file with mode: 0644]
mcs/build/profiles/xbuild_12.make [new file with mode: 0644]
mcs/class/Facades/Makefile
mcs/class/Facades/System.Dynamic.Runtime/TypeForwarders.cs
mcs/class/Facades/System.Linq.Expressions/TypeForwarders.cs
mcs/class/Facades/System.ObjectModel/TypeForwarders.cs
mcs/class/Mainsoft.Web/Mainsoft.Web.Security/DerbyRoleProvider.cs
mcs/class/Makefile
mcs/class/Managed.Windows.Forms/System.Windows.Forms/TextControl.cs
mcs/class/Microsoft.Build.Engine/Assembly/AssemblyInfo.cs
mcs/class/Microsoft.Build.Engine/Makefile
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildItem.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Engine.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Project.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Toolset.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine.dll.sources
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/BuildItemTest.cs
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/Consts.cs
mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-3.5 [deleted file]
mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-4.0 [deleted file]
mcs/class/Microsoft.Build.Framework/Assembly/AssemblyInfo.cs
mcs/class/Microsoft.Build.Framework/Makefile
mcs/class/Microsoft.Build.Framework/Microsoft.Build.Framework.dll.sources
mcs/class/Microsoft.Build.Tasks/Assembly/AssemblyInfo.cs
mcs/class/Microsoft.Build.Tasks/Makefile
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks.dll.sources
mcs/class/Microsoft.Build.Utilities/Assembly/AssemblyInfo.cs
mcs/class/Microsoft.Build.Utilities/Makefile
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities.dll.sources
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ProcessService.cs
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/TargetDotNetFrameworkVersion.cs
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolLocationHelper.cs
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ReservedNameUtils.cs
mcs/class/Microsoft.Build/Assembly/AssemblyInfo.cs
mcs/class/Microsoft.Build/Makefile
mcs/class/Microsoft.Build/Microsoft.Build.Evaluation/ProjectCollection.cs
mcs/class/Microsoft.Build/Microsoft.Build.dll.sources
mcs/class/Mono.CSharp/Makefile
mcs/class/Mono.CSharp/monotouch.cs [new file with mode: 0644]
mcs/class/Mono.CSharp/monotouch_Mono.CSharp.dll.sources [new file with mode: 0644]
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/StructMirror.cs
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs
mcs/class/Mono.Debugger.Soft/Test/dtest-app.cs
mcs/class/Mono.Debugger.Soft/Test/dtest.cs
mcs/class/Mono.Dynamic.Interpreter/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/Mono.Dynamic.Interpreter/Makefile [new file with mode: 0644]
mcs/class/Mono.Dynamic.Interpreter/Mono.Dynamic.Interpreter.dll.sources [new file with mode: 0644]
mcs/class/Mono.Posix/Mono.Unix.Native/Syscall.cs
mcs/class/Mono.XBuild.Tasks/Makefile
mcs/class/Moonlight.Build.Tasks/ChangeLog [deleted file]
mcs/class/Moonlight.Build.Tasks/Makefile [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_2_0.csproj [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_4_0.csproj [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_4_5.csproj [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks.dll.sources [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/ChangeLog [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/CreateTestPage.cs [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateMoonlightManifest.cs [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateXap.cs [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/PreviewTemplate.html [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/Respack.cs [deleted file]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/XamlG.cs [deleted file]
mcs/class/System.ComponentModel.Composition.4.5/Makefile
mcs/class/System.ComponentModel.DataAnnotations/Makefile
mcs/class/System.ComponentModel.DataAnnotations/xammac_System.ComponentModel.DataAnnotations.dll.sources [new file with mode: 0644]
mcs/class/System.Core/Makefile
mcs/class/System.Core/System.Linq.Expressions.Interpret/LambdaCompiler.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq.jvm/ChangeLog [deleted file]
mcs/class/System.Core/System.Linq.jvm/Conversion.cs [deleted file]
mcs/class/System.Core/System.Linq.jvm/ExpressionInterpreter.cs [deleted file]
mcs/class/System.Core/System.Linq.jvm/Math.cs [deleted file]
mcs/class/System.Core/System.Linq.jvm/Runner.cs [deleted file]
mcs/class/System.Core/System.Runtime.CompilerServices/ExecutionScope.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Multiply.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Subtract.cs
mcs/class/System.Core/dynamic_System.Core.dll.sources
mcs/class/System.Core/interpreter_System.Core.dll.sources [new file with mode: 0644]
mcs/class/System.Core/mobile_System.Core.dll.sources
mcs/class/System.Core/mobile_static_System.Core.dll.sources [deleted file]
mcs/class/System.Core/monotouch_System.Core.dll.sources
mcs/class/System.Core/net_4_0_System.Core.dll.sources
mcs/class/System.Core/static_System.Core.dll.sources [deleted file]
mcs/class/System.Core/xammac_System.Core.dll.sources [new file with mode: 0644]
mcs/class/System.Data.OracleClient/Test/TestOracleClient.cs
mcs/class/System.Data.Services.Client/xammac_System.Data.Services.Client.dll.sources [new file with mode: 0644]
mcs/class/System.Data/Makefile
mcs/class/System.Data/xammac_System.Data.dll.sources [new file with mode: 0644]
mcs/class/System.DirectoryServices/Test/System.DirectoryServices/DirectoryServicesSearchResultTest.cs
mcs/class/System.Interactive.Async/Makefile
mcs/class/System.Interactive.Providers/Makefile
mcs/class/System.Interactive/Makefile
mcs/class/System.Json.Microsoft/Makefile
mcs/class/System.Net.Http/System.Net.Http.Headers/AuthenticationHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/CollectionParser.cs [new file with mode: 0644]
mcs/class/System.Net.Http/System.Net.Http.Headers/ContentDispositionHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/EntityTagHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/HeaderInfo.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/Lexer.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/MediaTypeHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/MediaTypeWithQualityHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/NameValueHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/NameValueWithParametersHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/Parser.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/ProductHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/ProductInfoHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/StringWithQualityHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/TransferCodingHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/TransferCodingWithQualityHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/ViaHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.Headers/WarningHeaderValue.cs
mcs/class/System.Net.Http/System.Net.Http.dll.sources
mcs/class/System.Net.Http/Test/System.Net.Http.Headers/NameValueHeaderValueTest.cs
mcs/class/System.Net.Http/Test/System.Net.Http/HttpRequestMessageTest.cs
mcs/class/System.Net.Http/Test/System.Net.Http/HttpResponseMessageTest.cs
mcs/class/System.Net.Http/Test/System.Net.Http/StreamContentTest.cs
mcs/class/System.Net.Http/monotouch_System.Net.Http.dll.sources
mcs/class/System.Reactive.Core/Makefile
mcs/class/System.Reactive.Debugger/Makefile
mcs/class/System.Reactive.Experimental/Makefile
mcs/class/System.Reactive.Interfaces/Makefile
mcs/class/System.Reactive.Linq/Makefile
mcs/class/System.Reactive.Observable.Aliases/Makefile
mcs/class/System.Reactive.PlatformServices/Makefile
mcs/class/System.Reactive.Providers/Makefile
mcs/class/System.Runtime.Serialization/xammac_System.Runtime.Serialization.dll.sources [new file with mode: 0644]
mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/JsonQueryStringConverter.cs
mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/QueryStringConverter.cs
mcs/class/System.ServiceModel.Web/System.ServiceModel.Web/OutgoingWebRequestContext.cs
mcs/class/System.ServiceModel.Web/System.ServiceModel/WebHttpBinding.cs
mcs/class/System.ServiceModel.Web/System/UriTemplate.cs
mcs/class/System.ServiceModel.Web/System/UriTemplateMatch.cs
mcs/class/System.ServiceModel.Web/Test/System.ServiceModel.Web/WebOperationContextTest.cs
mcs/class/System.ServiceModel.Web/xammac_System.ServiceModel.Web.dll.sources [new file with mode: 0644]
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs
mcs/class/System.ServiceModel/xammac_System.ServiceModel.dll.sources [new file with mode: 0644]
mcs/class/System.Transactions/Makefile
mcs/class/System.Transactions/System.Transactions/Enlistment.cs
mcs/class/System.Transactions/System.Transactions/PreparingEnlistment.cs
mcs/class/System.Web.Services/Makefile
mcs/class/System.Web.Services/xammac_System.Web.Services.dll.sources [new file with mode: 0644]
mcs/class/System.Web/System.Web.Security/SqlRoleProvider.cs
mcs/class/System.XML/Test/System.Xml/XmlNodeReaderTests.cs
mcs/class/System.XML/Test/System.Xml/XmlTextReaderTests.cs
mcs/class/System.XML/Test/System.Xml/nist_dom/fundamental/NamedNodeMap/NamedNodeMap.cs
mcs/class/System.XML/xammac_System.Xml.dll.sources [new file with mode: 0644]
mcs/class/System/Documentation/en/System.Net/IPAddress.xml
mcs/class/System/Makefile
mcs/class/System/System.Collections.Generic/LinkedList.cs
mcs/class/System/System.ComponentModel/BindingList.cs
mcs/class/System/System.IO/FileSystemWatcher.cs
mcs/class/System/System.Net.NetworkInformation/NetworkChange.cs
mcs/class/System/System.Net/IPAddress.cs
mcs/class/System/Test/System.Collections.Generic/LinkedListTest.cs
mcs/class/System/Test/System.ComponentModel/BindingListTest.cs
mcs/class/System/Test/System.Net/IPAddressTest.cs
mcs/class/System/mobile_System.dll.sources
mcs/class/System/monodroid_System.dll.sources
mcs/class/System/xammac_System.dll.sources [new file with mode: 0644]
mcs/class/corlib/System.IO/BinaryReader.cs
mcs/class/corlib/System.IO/Directory.cs
mcs/class/corlib/System.IO/Stream.cs
mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs
mcs/class/corlib/System.Reflection.Emit/AssemblyBuilderAccess.cs
mcs/class/corlib/System.Reflection.Emit/FlowControl.cs
mcs/class/corlib/System.Reflection.Emit/Label.cs
mcs/class/corlib/System.Reflection.Emit/MethodToken.cs
mcs/class/corlib/System.Reflection.Emit/ModuleBuilder.cs
mcs/class/corlib/System.Reflection.Emit/OpCode.cs
mcs/class/corlib/System.Reflection.Emit/OpCodeNames.cs
mcs/class/corlib/System.Reflection.Emit/OpCodeType.cs
mcs/class/corlib/System.Reflection.Emit/OpCodes.cs
mcs/class/corlib/System.Reflection.Emit/OperandType.cs
mcs/class/corlib/System.Reflection.Emit/PEFileKinds.cs
mcs/class/corlib/System.Reflection.Emit/StackBehaviour.cs
mcs/class/corlib/System.Threading.Tasks/Task.cs
mcs/class/corlib/System.Threading.Tasks/TaskContinuation.cs
mcs/class/corlib/System.Threading/CancellationTokenSource.cs
mcs/class/corlib/Test/System.IO/BinaryReaderTest.cs
mcs/class/corlib/Test/System.IO/FileTest.cs
mcs/class/corlib/Test/System.Threading/CancellationTokenSourceTest.cs
mcs/class/corlib/Test/System/AppDomainTest.cs
mcs/class/dlr/README [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Actions/Dummy.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/BinaryExpression.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/ConstantExpression.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/LightLambdaExpression.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/UnaryExpression.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/Utils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/DebugOptions.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.Generated.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/BranchLabel.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/ILightCallSiteBinder.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AddInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AndInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.Generated.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ControlFlowInstructions.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DivInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructionN.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructions.Generated.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicSplatInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/EqualInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionFactory.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LabelInfo.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ModInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/MulInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NegateInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotEqualInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NumericConvertInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShlInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShrInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/StackOperations.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/SubInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/TypeOperations.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Interpreter.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightCompiler.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LocalVariables.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LoopCompiler.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/RuntimeVariables.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/BigIntegerV4.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Math/Complex64.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/MultiRuntimeAwareAttribute.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/PerfTrack.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/DynamicNull.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ExceptionHelpers.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ScriptingRuntimeHelpers.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ArrayUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/Assert.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CacheDict.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionExtensions.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/CollectionUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ContractUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/DynamicUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionFactory.Generated.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/HybridReferenceDictionary.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ListEqualityComparer.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/MathUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReflectionUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/StringUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/TypeUtils.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/LambdaExpression.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewExpression.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs
mcs/class/dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Scripting/InvalidImplementationException.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Scripting/PlatformAdaptationLayer.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/NotNullAttribute.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Scripting/Runtime/ParamDictionaryAttribute.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Scripting/Stubs.cs [new file with mode: 0644]
mcs/errors/CS0012-22-lib.il [new file with mode: 0644]
mcs/errors/Makefile
mcs/errors/cs0012-22.cs [new file with mode: 0644]
mcs/errors/cs0029-35.cs [new file with mode: 0644]
mcs/errors/cs0165-44.cs [new file with mode: 0644]
mcs/errors/cs0220-4.cs [new file with mode: 0644]
mcs/errors/cs1060-4.cs [new file with mode: 0644]
mcs/errors/cs1654-5.cs [new file with mode: 0644]
mcs/errors/known-issues-net_4_5
mcs/mcs/assign.cs
mcs/mcs/context.cs
mcs/mcs/driver.cs
mcs/mcs/dynamic.cs
mcs/mcs/ecore.cs
mcs/mcs/eval.cs
mcs/mcs/expression.cs
mcs/mcs/ikvm.cs
mcs/mcs/import.cs
mcs/mcs/location.cs
mcs/mcs/membercache.cs
mcs/mcs/reflection.cs
mcs/mcs/statement.cs
mcs/mcs/support.cs
mcs/tests/Makefile
mcs/tests/dlls/test-883.il [new file with mode: 0644]
mcs/tests/gtest-lambda-32.cs [new file with mode: 0644]
mcs/tests/test-829.cs
mcs/tests/test-883-lib.cs [new file with mode: 0644]
mcs/tests/test-883.cs [new file with mode: 0644]
mcs/tests/ver-il-net_4_5.xml
mcs/tools/corcompare/mono-api-info.cs
mcs/tools/csharp/repl.cs
mcs/tools/linker/Descriptors/System.Core.xml [new file with mode: 0644]
mcs/tools/linker/Makefile
mcs/tools/linker/README
mcs/tools/mdoc/Test/en.expected.delete/index.xml
mcs/tools/mdoc/Test/en.expected.importecmadoc/index.xml
mcs/tools/mdoc/Test/en.expected.importslashdoc/index.xml
mcs/tools/mdoc/Test/en.expected.since/index.xml
mcs/tools/mdoc/Test/en.expected/index.xml
mcs/tools/mkbundle/mkbundle.cs
mcs/tools/mkbundle/template_z.c
mcs/tools/monop/outline.cs
mcs/tools/xbuild/ErrorUtilities.cs
mcs/tools/xbuild/Makefile
mcs/tools/xbuild/SolutionParser.cs
mcs/tools/xbuild/XBuildConsts.cs [new file with mode: 0644]
mcs/tools/xbuild/data/12.0/Microsoft.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/data/12.0/Microsoft.Common.tasks [new file with mode: 0644]
mcs/tools/xbuild/data/2.0/Microsoft.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/data/2.0/Microsoft.Common.tasks [new file with mode: 0644]
mcs/tools/xbuild/data/3.5/Microsoft.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/data/3.5/Microsoft.Common.tasks [new file with mode: 0644]
mcs/tools/xbuild/data/4.0/Microsoft.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/data/4.0/Microsoft.Common.tasks [new file with mode: 0644]
mcs/tools/xbuild/data/MSBuild/Microsoft.Build.CommonTypes.xsd [new file with mode: 0644]
mcs/tools/xbuild/data/MSBuild/Microsoft.Build.Core.xsd [new file with mode: 0644]
mcs/tools/xbuild/data/Microsoft.Build.xsd [new file with mode: 0644]
mcs/tools/xbuild/data/Microsoft.CSharp.targets [new file with mode: 0644]
mcs/tools/xbuild/data/Microsoft.VisualBasic.targets [new file with mode: 0644]
mcs/tools/xbuild/data/xbuild.exe.config.in [new file with mode: 0644]
mcs/tools/xbuild/data/xbuild.rsp [new file with mode: 0644]
mcs/tools/xbuild/frameworks/net_2.0.xml [new file with mode: 0644]
mcs/tools/xbuild/frameworks/net_3.0.xml [new file with mode: 0644]
mcs/tools/xbuild/frameworks/net_3.5.xml [new file with mode: 0644]
mcs/tools/xbuild/frameworks/net_4.0.xml [new file with mode: 0644]
mcs/tools/xbuild/frameworks/net_4.0_client.xml [new file with mode: 0644]
mcs/tools/xbuild/frameworks/net_4.5.xml [new file with mode: 0644]
mcs/tools/xbuild/targets/Microsoft.Portable.CSharp_4.0.targets [new file with mode: 0644]
mcs/tools/xbuild/targets/Microsoft.Portable.CSharp_4.5.targets [new file with mode: 0644]
mcs/tools/xbuild/targets/Microsoft.WebApplication.targets [new file with mode: 0644]
mcs/tools/xbuild/xbuild.exe.sources
mcs/tools/xbuild/xbuild.make [new file with mode: 0644]
mcs/tools/xbuild/xbuild/2.0/FrameworkList.xml [deleted file]
mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets [deleted file]
mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.tasks [deleted file]
mcs/tools/xbuild/xbuild/3.5/FrameworkList.xml [deleted file]
mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets [deleted file]
mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.tasks [deleted file]
mcs/tools/xbuild/xbuild/4.0/FrameworkList.xml [deleted file]
mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets [deleted file]
mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.tasks [deleted file]
mcs/tools/xbuild/xbuild/4.0/Microsoft.Portable.CSharp.targets [deleted file]
mcs/tools/xbuild/xbuild/4.5/FrameworkList.xml [deleted file]
mcs/tools/xbuild/xbuild/4.5/Microsoft.Portable.CSharp.targets [deleted file]
mcs/tools/xbuild/xbuild/FrameworkList-3.0.xml [deleted file]
mcs/tools/xbuild/xbuild/MSBuild/Microsoft.Build.CommonTypes.xsd [deleted file]
mcs/tools/xbuild/xbuild/MSBuild/Microsoft.Build.Core.xsd [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.Build.xsd [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.Portable.CSharp.targets [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.Silverlight.CSharp.targets [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.Silverlight.Common.targets [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.Silverlight.VisualBasic.targets [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.VisualBasic.targets [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.WebApplication.targets [deleted file]
mcs/tools/xbuild/xbuild/xbuild.rsp [deleted file]
mcs/tools/xbuild/xbuild_targets.make [deleted file]
mcs/tools/xbuild/xbuild_test.make [new file with mode: 0644]
mono/io-layer/io.c
mono/io-layer/processes.c
mono/io-layer/sockets.c
mono/io-layer/thread-private.h
mono/io-layer/threads.h
mono/io-layer/wthreads.c
mono/metadata/Makefile.am.in
mono/metadata/appdomain.c
mono/metadata/attach.c
mono/metadata/boehm-gc.c
mono/metadata/class.c
mono/metadata/culture-info-tables.h
mono/metadata/debug-helpers.c
mono/metadata/domain.c
mono/metadata/icall.c
mono/metadata/loader.c
mono/metadata/marshal.c
mono/metadata/metadata-internals.h
mono/metadata/sgen-gc.c
mono/metadata/sgen-os-mach.c
mono/metadata/sgen-qsort.c
mono/metadata/sgen-stw.c
mono/metadata/threadpool.c
mono/metadata/threads-types.h
mono/metadata/threads.c
mono/mini/Makefile.am.in
mono/mini/alias-analysis.c
mono/mini/aot-compiler.c
mono/mini/aot-runtime.c
mono/mini/cpu-amd64.md
mono/mini/debugger-agent.c
mono/mini/driver.c
mono/mini/dwarfwriter.c
mono/mini/exceptions-x86.c
mono/mini/gshared.cs
mono/mini/method-to-ir.c
mono/mini/mini-amd64.c
mono/mini/mini-arm.c
mono/mini/mini-darwin.c
mono/mini/mini-exceptions.c
mono/mini/mini-generic-sharing.c
mono/mini/mini-native-types.c [new file with mode: 0644]
mono/mini/mini-ppc.c
mono/mini/mini-trampolines.c
mono/mini/mini-unwind.h
mono/mini/mini-x86.c
mono/mini/mini.c
mono/mini/mini.h
mono/mini/trace.c
mono/mini/tramp-arm.c
mono/mini/tramp-x86.c
mono/tests/marshal7.cs
mono/utils/atomic.h
mono/utils/mono-compiler.h
mono/utils/mono-filemap.c
mono/utils/mono-proclib.c
mono/utils/mono-threads-posix.c
mono/utils/mono-threads-windows.c
mono/utils/mono-threads.c
mono/utils/mono-threads.h
runtime/Makefile.am
scripts/Makefile.am
scripts/xbuild.in [new file with mode: 0644]
tools/locale-builder/Driver.cs

index a4a959d1c48b94c3eaecdcb78bc8b6d937f7fdc6..af638365a062d49cb26b6e7cd6395e664ba952cd 100644 (file)
@@ -11,12 +11,16 @@ else
 if ONLY_MONOTOUCH
 SUBDIRS = $(MONOTOUCH_SUBDIRS) runtime
 else
+if ONLY_XAMMAC
+SUBDIRS = $(libgc_dir) eglib/src mono runtime
+else
 SUBDIRS = po $(libgc_dir) eglib mono $(ikvm_native_dir) support data runtime scripts man samples msvc $(docs_dir)
 # Keep in sync with SUBDIRS
 ## 'tools' is not normally built
 DIST_SUBDIRS = m4 po libgc eglib mono ikvm-native support data runtime scripts man samples tools msvc docs
 endif
 endif
+endif
 
 all: update_submodules
 
index d62e6a3f6beded6eb70ca239e8890952a0ecb759..ad5ac82cfaebe1c55d308f8ea779b264582a7eac 100644 (file)
@@ -215,6 +215,9 @@ case "$host" in
                CFLAGS="$CFLAGS -DPAGE_SIZE=4096 -DS_IWRITE=S_IWUSR"
                CXXFLAGS="$CXXFLAGS -DPAGE_SIZE=4096 -DS_IWRITE=S_IWUSR"
 
+               # The configure check can't detect this
+               AC_DEFINE(HAVE_LARGE_FILE_SUPPORT, 1, [Have large file support])
+
                # to bypass the underscore linker check, can't work when cross-compiling
                mono_cv_uscore=yes
                mono_cv_clang=no
@@ -949,6 +952,15 @@ if test x$has_extension_module != xno ; then
        AC_MSG_NOTICE([Enabling mono extension module.])
 fi
 
+AC_ARG_ENABLE(gsharing, [  --enable-gsharing Enable gsharing], enable_gsharing=$enableval, enable_gsharing=no)
+if test x$enable_gsharing = xyes; then
+       AC_DEFINE(MONO_GSHARING,1,[Gsharing])
+fi
+
+AC_ARG_ENABLE(native-types, [  --enable-native-types Enable native types], enable_native_types=$enableval, enable_native_types=no)
+if test x$enable_native_types = xyes; then
+       AC_DEFINE(MONO_NATIVE_TYPES,1,[native types])
+fi
 
 AC_MSG_CHECKING(for visibility __attribute__)
 AC_COMPILE_IFELSE([
@@ -3167,7 +3179,7 @@ AC_ARG_WITH(profile4,  [  --with-profile4=yes,no          If you want to install
 AC_ARG_WITH(profile4_5,[  --with-profile4_5=yes,no        If you want to install the 4.5 FX (defaults to yes)],                [], [with_profile4_5=yes])
 AC_ARG_WITH(monodroid, [  --with-monodroid=yes,no         If you want to build the MonoDroid assemblies (defaults to no)],     [], [with_monodroid=no])
 AC_ARG_WITH(monotouch, [  --with-monotouch=yes,no,only    If you want to build the MonoTouch assemblies (defaults to no)],     [], [with_monotouch=no])
-AC_ARG_WITH(mobile,    [  --with-mobile=yes,no            If you want to build the Mobile assemblies (defaults to no)],        [], [with_mobile=no])
+AC_ARG_WITH(xammac,    [  --with-xammac=yes,no,only       If you want to build the Xamarin.Mac assemblies (defaults to no)],   [], [with_xammac=no])
 
 OPROFILE=no
 AC_ARG_WITH(oprofile,[  --with-oprofile=no,<oprofile install dir>   Enable oprofile support (defaults to no)],[
@@ -3243,6 +3255,7 @@ if test x$cross_compiling = xyes -o x$enable_mcs_build = xno; then
    with_profile4_5=no
    with_monodroid=no
    with_monotouch=no
+   with_xammac=no
 fi
 
 if test x$DISABLE_MCS_DOCS = xyes; then
@@ -3266,8 +3279,9 @@ AM_CONDITIONAL(INSTALL_4_0, [test "x$with_profile4" = xyes])
 AM_CONDITIONAL(INSTALL_4_5, [test "x$with_profile4_5" = xyes])
 AM_CONDITIONAL(INSTALL_MONODROID, [test "x$with_monodroid" != "xno"])
 AM_CONDITIONAL(INSTALL_MONOTOUCH, [test "x$with_monotouch" != "xno"])
-AM_CONDITIONAL(INSTALL_MOBILE, [test "x$with_mobile" = xyes])
+AM_CONDITIONAL(INSTALL_XAMMAC, [test "x$with_xammac" != "xno"])
 AM_CONDITIONAL(ONLY_MONOTOUCH, [test "x$with_monotouch" = "xonly"])
+AM_CONDITIONAL(ONLY_XAMMAC, [test "x$with_xammac" = "xonly"])
 
 AM_CONDITIONAL(MIPS_GCC, test ${TARGET}${ac_cv_prog_gcc} = MIPSyes)
 AM_CONDITIONAL(MIPS_SGI, test ${TARGET}${ac_cv_prog_gcc} = MIPSno)
@@ -3660,6 +3674,9 @@ fi
     if test -z "$INSTALL_MONOTOUCH_TRUE"; then :
                default_profile=monotouch
     fi
+       if test -z "$INSTALL_XAMMAC_TRUE"; then :
+               default_profile=xammac
+       fi
     if test -z "$INSTALL_4_5_TRUE"; then :
                default_profile=net_4_5
     fi
@@ -3711,6 +3728,7 @@ echo "
        .NET 4.5:      $with_profile4_5
        MonoDroid:     $with_monodroid
        MonoTouch:     $with_monotouch
+       Xamarin.Mac:   $with_xammac
        JNI support:   $jdk_headers_found
        libgdiplus:    $libgdiplus_msg
        zlib:          $zlib_msg
index 601b4dab269b6c22fb5caea6349ae7db3347b2a3..30e26a9014b77605ffe2023106bd19483edbaa0b 100644 (file)
@@ -12,7 +12,8 @@ EXTRA_DIST =          \
        mono.pc.in mono-2.pc.in monosgen-2.pc.in mint.pc.in dotnet.pc.in dotnet35.pc.in wcf.pc.in monodoc.pc.in \
        mono-nunit.pc.in mono-cairo.pc.in mono-options.pc.in cecil.pc.in \
        mono-lineeditor.pc.in system.web.extensions_1.0.pc.in system.web.extensions.design_1.0.pc.in\
-       dtrace-prelink.sh mono.web.pc.in system.web.mvc.pc.in system.web.mvc2.pc.in system.web.mvc3.pc.in aspnetwebstack.pc.in reactive.pc.in \
+       dtrace-prelink.sh mono.web.pc.in system.web.mvc.pc.in system.web.mvc2.pc.in system.web.mvc3.pc.in aspnetwebstack.pc.in \
+       reactive.pc.in xbuild12.pc \
        net_1_1/machine.config \
        gdb/mono-gdb.py \
        gdb/gdb-python.diff
@@ -28,10 +29,10 @@ endif
 if JIT_SUPPORTED
 if INTERP_SUPPORTED
 pkgconfig_DATA= mono.pc mono-2.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc system.web.mvc3.pc aspnetwebstack.pc reactive.pc $(SGENPCFILE)
+               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc system.web.mvc3.pc aspnetwebstack.pc reactive.pc xbuild12.pc $(SGENPCFILE)
 else
 pkgconfig_DATA= mono.pc mono-2.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc system.web.mvc3.pc aspnetwebstack.pc reactive.pc $(SGENPCFILE)
+               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc system.web.mvc3.pc aspnetwebstack.pc reactive.pc xbuild12.pc $(SGENPCFILE)
 endif
 else
 pkgconfig_DATA= mint.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc
index 32e075a3856e6aee10ab22d48ccba0ca89b7e918..cf457fc207bac9f58a5f335a5f8bc31aa45f629b 100644 (file)
@@ -28,4 +28,6 @@
        </dllmap>
        <dllmap dll="gdiplus" target="@prefix@/lib/libgdiplus@libsuffix@" os="!windows"/>
        <dllmap dll="gdiplus.dll" target="@prefix@/lib/libgdiplus@libsuffix@"  os="!windows"/>
+       <dllmap dll="gdi32" target="@prefix@/lib/libgdiplus@libsuffix@" os="!windows"/>
+       <dllmap dll="gdi32.dll" target="@prefix@/lib/libgdiplus@libsuffix@" os="!windows"/>
 </configuration>
diff --git a/data/xbuild12.pc b/data/xbuild12.pc
new file mode 100644 (file)
index 0000000..35816fd
--- /dev/null
@@ -0,0 +1,7 @@
+bindir=${pcfiledir}/../mono/xbuild/12.0/bin
+
+Name: XBuild 12.0
+Description: XBuild/MSBuild 12.0
+Version: 12.0
+Libs: -r:${bindir}/Microsoft.Build.Engine.dll -r:${bindir}/Microsoft.Build.Framework.dll -r:${bindir}/Microsoft.Build.Tasks.v12.0.dll -r:${bindir}/Microsoft.Build.Utilities.v12.0.dll -r:${bindir}/Microsoft.Build.dll
+
index 14343494d80eb5660d5aadd08fcea92814c5b7ac..5302f427925453496b43d0b4babb88daacbd9bf1 100644 (file)
@@ -216,8 +216,8 @@ cont:
 gchar *
 g_find_program_in_path (const gchar *program)
 {
-       char *p = g_strdup (g_getenv ("PATH"));
-       char *x = p, *l;
+       char *p;
+       char *x, *l;
        gchar *curdir = NULL;
        char *save = NULL;
 #ifdef G_OS_WIN32
@@ -228,6 +228,7 @@ g_find_program_in_path (const gchar *program)
 #endif
 
        g_return_val_if_fail (program != NULL, NULL);
+       x = p = g_strdup (g_getenv ("PATH"));
 
        if (x == NULL || *x == '\0') {
                curdir = g_get_current_dir ();
index 0b0e4235a7aabd2f0cd4e8b1b1af368122103e56..b53530a824b8b8934f8046e166c63bf184fbe93f 100644 (file)
@@ -1417,9 +1417,9 @@ small embedded systems.
 The default is 180 seconds.
 .TP
 \fBMONO_THREADS_PER_CPU\fR
-The maximum number of threads in the general threadpool will be
-20 + (MONO_THREADS_PER_CPU * number of CPUs). The default value for this
-variable is 10.
+The minimum number of threads in the general threadpool will be 
+MONO_THREADS_PER_CPU * number of CPUs. The default value for this
+variable is 1.
 .TP
 \fBMONO_XMLSERIALIZER_THS\fR
 Controls the threshold for the XmlSerializer to produce a custom
index df6b9a117d554b273b757a41e28ae10ae97dfc37..78af02bc44f60b892ed897af08dfdabac2393803 100644 (file)
@@ -10,10 +10,12 @@ net_2_0_SUBDIRS := build class nunit24 ilasm tools tests errors docs
 monodroid_SUBDIRS := build class
 monotouch_SUBDIRS := build class
 monotouch_runtime_SUBDIRS := build class
+xammac_SUBDIRS := build class
 mobile_SUBDIRS := build class
 net_3_5_SUBDIRS := build class tools/xbuild
 net_4_0_SUBDIRS := build class
 net_4_5_SUBDIRS := build mcs class nunit24 ilasm tools tests errors docs
+xbuild_12_SUBDIRS := build class tools/xbuild
 
 # List of test subdirs that should pass 100%
 centum_tests := \
@@ -85,7 +87,7 @@ dir-check:
 
 # fun specialty targets
 
-PROFILES = net_2_0 net_3_5 net_4_0 net_4_5
+PROFILES = net_2_0 net_3_5 net_4_0 net_4_5 xbuild_12
 
 .PHONY: all-profiles $(STD_TARGETS:=-profiles)
 all-profiles $(STD_TARGETS:=-profiles): %-profiles: profiles-do--%
@@ -104,12 +106,14 @@ profiles-do--run-test:
 
 # Orchestrate the bootstrap here.
 _boot_ = all clean install
+$(_boot_:%=profile-do--xbuild_12--%):         profile-do--xbuild_12--%:         profile-do--net_4_5--%
 $(_boot_:%=profile-do--net_4_5--%):           profile-do--net_4_5--%:           profile-do--build--%
 $(_boot_:%=profile-do--net_4_0--%):           profile-do--net_4_0--%:           profile-do--build--%
 $(_boot_:%=profile-do--net_3_5--%):           profile-do--net_3_5--%:           profile-do--net_2_0--%
 $(_boot_:%=profile-do--monodroid--%):         profile-do--monodroid--%:         profile-do--build--%
 $(_boot_:%=profile-do--monotouch--%):         profile-do--monotouch--%:         profile-do--build--%
 $(_boot_:%=profile-do--monotouch_runtime--%):  profile-do--monotouch_runtime--%:  profile-do--build--%
+$(_boot_:%=profile-do--xammac--%):            profile-do--xammac--%:            profile-do--build--%
 $(_boot_:%=profile-do--mobile--%):            profile-do--mobile--%:         profile-do--build--%
 $(_boot_:%=profile-do--net_2_0--%):           profile-do--net_2_0--%:           profile-do--build--%
 $(_boot_:%=profile-do--build--%):             profile-do--build--%:             profile-do--basic--%
index c35e34b26bfdcab632fd831376cfa126255b5141..ce026ae275fd57a1ad44b124c96abf5fd35b5f6b 100644 (file)
@@ -21,7 +21,8 @@ PROFILES = \
        net_2_0 \
        net_3_5 \
        net_4_0 \
-       net_4_5
+       net_4_5 \
+       xbuild_12
 
 COMMON_SRCS = \
        Consts.cs.in                    \
index 9504c8b2f8a2a6c9bf60fcbb2e0bc9377f0b9aea..7336ced7b7bb07cbc51d343dbdfb5ef900a1ead0 100644 (file)
@@ -12,7 +12,7 @@ profile-check:
        @:
 
 DEFAULT_REFERENCES = -r:mscorlib.dll
-PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1 -d:NET_3_5 -d:NET_4_0 -d:NET_4_5 -d:MOBILE -d:MONODROID -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) $(DEFAULT_REFERENCES) $(PLATFORM_DEBUG_FLAGS)
+PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1 -d:NET_3_5 -d:NET_4_0 -d:NET_4_5 -d:MOBILE -d:MOBILE_DYNAMIC -d:MONODROID -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) $(DEFAULT_REFERENCES) $(PLATFORM_DEBUG_FLAGS)
 FRAMEWORK_VERSION = 2.1
 NO_TEST = yes
 
index 9f82811018f495c016c9ee62ab9e73a00dc38648..f438e805f0d054115e869b8e7042725b92c83b2b 100644 (file)
@@ -14,7 +14,7 @@ profile-check:
        @:
 
 DEFAULT_REFERENCES = -r:mscorlib.dll
-PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1 -d:NET_3_5 -d:NET_4_0 -d:NET_4_5 -d:MOBILE -d:MONOTOUCH -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) $(DEFAULT_REFERENCES) $(PLATFORM_DEBUG_FLAGS)
+PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1 -d:NET_3_5 -d:NET_4_0 -d:NET_4_5 -d:MOBILE -d:MONOTOUCH -D:DISABLE_REMOTING -d:DISABLE_COM -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) $(DEFAULT_REFERENCES) $(PLATFORM_DEBUG_FLAGS)
 
 FRAMEWORK_VERSION = 2.1
 
index 488017814fa90a2085791040072b6c25e847c7be..e3be2c83438dcde1e62a242fe0d1a9a166fbb77b 100644 (file)
@@ -13,3 +13,4 @@ DEFAULT_REFERENCES = -r:mscorlib.dll
 PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) $(DEFAULT_REFERENCES) $(PLATFORM_DEBUG_FLAGS)
 
 FRAMEWORK_VERSION = 2.0
+XBUILD_VERSION = 2.0
index 0f26f3903832fb7e42ae31557c28ab4a19efded4..97176892a4a74f3d83a639587e95973f41bbd46e 100644 (file)
@@ -13,6 +13,7 @@ DEFAULT_REFERENCES = -r:mscorlib.dll
 PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_3_5 -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) -lib:$(topdir)/class/lib/net_2_0 $(DEFAULT_REFERENCES) $(PLATFORM_DEBUG_FLAGS)
 
 FRAMEWORK_VERSION = 3.5
+XBUILD_VERSION = 3.5
 
 TEST_HARNESS = $(topdir)/class/lib/net_2_0/nunit-console.exe
 TEST_MONO_PATH = $(topdir)/class/lib/net_2_0
index 0a26e1b9a0224d521d94d7927d02dbf8ad80028d..a5bec4cd2cccb07c35abc0edb544ed1b0ff3fd4f 100644 (file)
@@ -14,5 +14,6 @@ DEFAULT_REFERENCES = -r:mscorlib.dll
 PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_3_0 -d:NET_3_5 -d:NET_4_0 -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) $(DEFAULT_REFERENCES)
 
 FRAMEWORK_VERSION = 4.0
+XBUILD_VERSION = 4.0
 
 LIBRARY_INSTALL_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)
index c153792f1b9f0fda4279aa4f96b6d6953848e58b..ad921e705ea23954807e40962b2e6cef80d3875b 100644 (file)
@@ -14,3 +14,4 @@ DEFAULT_REFERENCES = -r:mscorlib.dll
 PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_3_0 -d:NET_3_5 -d:NET_4_0 -d:NET_4_5 -nowarn:1699 -nostdlib -lib:$(topdir)/class/lib/$(PROFILE) $(DEFAULT_REFERENCES) $(PLATFORM_DEBUG_FLAGS)
 
 FRAMEWORK_VERSION = 4.5
+XBUILD_VERSION = 4.0
diff --git a/mcs/build/profiles/xammac.make b/mcs/build/profiles/xammac.make
new file mode 100644 (file)
index 0000000..d463a0f
--- /dev/null
@@ -0,0 +1,32 @@
+BOOTSTRAP_PROFILE = build
+
+BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_GMCS)
+MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_GMCS)
+
+# Use system resgen as we don't want local System.Windows.Forms dependency
+RESGEN = resgen2
+
+profile-check:
+       @:
+
+DEFAULT_REFERENCES = -r:mscorlib.dll
+
+PROFILE_MCS_FLAGS = \
+       -d:NET_1_1 \
+       -d:NET_2_0 \
+       -d:NET_2_1 \
+       -d:NET_3_5 \
+       -d:NET_4_0 \
+       -d:NET_4_5 \
+       -d:MOBILE \
+       -d:MOBILE_DYNAMIC \
+       -d:XAMMAC \
+       -nowarn:1699 \
+       -nostdlib \
+       -lib:$(topdir)/class/lib/$(PROFILE) \
+       $(DEFAULT_REFERENCES) \
+       $(PLATFORM_DEBUG_FLAGS)
+
+FRAMEWORK_VERSION = 2.1
+NO_TEST = yes
+NO_INSTALL = yes
diff --git a/mcs/build/profiles/xbuild_12.make b/mcs/build/profiles/xbuild_12.make
new file mode 100644 (file)
index 0000000..d3aff7e
--- /dev/null
@@ -0,0 +1,7 @@
+# -*- makefile -*-
+
+include $(topdir)/build/profiles/net_4_5.make
+
+PROFILE_MCS_FLAGS := $(PROFILE_MCS_FLAGS) -d:XBUILD_12 -lib:$(topdir)/class/lib/net_4_5
+
+XBUILD_VERSION = 12.0
index e8e8363b5ffe9fb9ffe46835aa84161666d83a09..d0e85464e45aee059b3f96ec1a5e6ecc80ce56da 100644 (file)
@@ -17,6 +17,8 @@ net_4_5_SUBDIRS = $(monotouch_SUBDIRS) System.Reflection.Emit.ILGeneration Syste
 
 monodroid_SUBDIRS = $(net_4_5_SUBDIRS)
 
+xammac_SUBDIRS = $(net_4_5_SUBDIRS)
+
 SUBDIRS = $(net_4_5_SUBDIRS)
 
 include $(MCS_BUILD_DIR)/rules.make
index ff800e52ef470a2d682b96e8a28c53c3c1394e3c..52c9043511937ce97bd89f4b6d110fa6bd33da70 100644 (file)
@@ -19,7 +19,7 @@
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 // 
-#if !FULL_AOT_RUNTIME
+
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Dynamic.BinaryOperationBinder))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Dynamic.BindingRestrictions))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Dynamic.CallInfo))]
@@ -46,6 +46,4 @@
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Runtime.CompilerServices.CallSiteBinder))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Runtime.CompilerServices.CallSiteHelpers))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Runtime.CompilerServices.DynamicAttribute))]
-#endif
-
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Runtime.CompilerServices.ConditionalWeakTable<,>))]
index 438486c963fdfdb43c72f7357417367fe1824328..db18f12782143efb95a74816fc3712c7632bd330 100644 (file)
@@ -20,7 +20,6 @@
 // THE SOFTWARE.
 // 
 
-#if !FULL_AOT_RUNTIME
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.BlockExpression))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.CatchBlock))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.DebugInfoExpression))]
@@ -36,7 +35,6 @@
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.SwitchExpression))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.SymbolDocumentInfo))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.TryExpression))]
-#endif
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.BinaryExpression))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.ConditionalExpression))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Linq.Expressions.ConstantExpression))]
index 2679bd038c5f09abde767c1171ff232b7e23e487..456c9db6eb1c89d5f2a7da8c6c37867115cbfbe0 100644 (file)
@@ -20,9 +20,7 @@
 // THE SOFTWARE.
 // 
 
-#if !MONOTOUCH
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Collections.ObjectModel.ReadOnlyDictionary<,>))]
-#endif
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Collections.ObjectModel.KeyedCollection<,>))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Collections.ObjectModel.ObservableCollection<>))]
 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Collections.ObjectModel.ReadOnlyObservableCollection<>))]
index e1af0e60e3fd5b36d38e35b8ae65ed7c33ec2578..cdce377b281f9f2cba730b786d5e6a9ae36eb961 100644 (file)
@@ -138,7 +138,7 @@ namespace Mainsoft.Web.Security
                                if (returnValue == 0)\r
                                        return true;\r
                                if (returnValue == 2)\r
-                                       return false; //role does not exists\r
+                                       return false; //role does not exist\r
                                else if (returnValue == 3 && throwOnPopulatedRole)\r
                                        throw new ProviderException (rolename + " is not empty");\r
                                else\r
index 79f1f9d618cb5a86c15cfe9d0aede507e04316a3..1e806388e326d6d34ce6091239d0e857867ee79d 100644 (file)
@@ -88,11 +88,6 @@ common_dirs := \
        SystemWebTestShim
 
 net_2_0_dirs := \
-       Microsoft.Build.Framework       \
-       Microsoft.Build.Utilities       \
-       Microsoft.Build.Engine          \
-       Mono.XBuild.Tasks                       \
-       Microsoft.Build.Tasks           \
        System.Xml.Linq                 \
        System.Runtime.Serialization    \
        System.Data.DataSetExtensions   \
@@ -115,7 +110,6 @@ net_2_0_dirs := \
        Mono.Tasklets                   \
        System.Dynamic                  \
        Mono.CSharp                     \
-       Moonlight.Build.Tasks           \
        System.Net                              \
        System.Json
 
@@ -167,20 +161,24 @@ monodroid_dirs := \
        Microsoft.CSharp \
        System.Net.Http
 
+xammac_dirs := \
+       Mono.CompilerServices.SymbolWriter      \
+       Mono.CSharp     \
+       Microsoft.CSharp \
+       System.Net.Http
+
 monotouch_runtime_dirs := \
        corlib
 
-net_3_5_only_dirs := \
-       Microsoft.Build.Framework       \
-       Microsoft.Build.Utilities       \
-       Microsoft.Build.Engine          \
-       Mono.XBuild.Tasks                       \
-       Microsoft.Build.Tasks
+monotouch_dirs := \
+       Mono.CSharp     \
+       Microsoft.CSharp \
+       Mono.Dynamic.Interpreter \
+       System.Core
 
 net_4_0_dirs := \
        System.Numerics         \
        Microsoft.CSharp        \
-       Microsoft.Build         \
        System.Windows.Forms.DataVisualization  \
        System.Xaml \
        WindowsBase \
@@ -235,22 +233,35 @@ net_4_5_dirs := \
        System.Windows \
        System.Xml.Serialization \
        $(pcl_facade_dirs)
-       
-net_2_0_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs) aot-compiler
+
+xbuild_2_0_dirs := \
+       Microsoft.Build.Framework       \
+       Microsoft.Build.Utilities       \
+       Microsoft.Build.Engine          \
+       Mono.XBuild.Tasks               \
+       Microsoft.Build.Tasks
+
+xbuild_4_0_dirs := \
+       $(xbuild_2_0_dirs)      \
+       Microsoft.Build
+
+net_2_0_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs) $(xbuild_2_0_dirs) aot-compiler
 monodroid_SUBDIRS := $(mobile_dirs) $(monodroid_dirs)
-monotouch_SUBDIRS := $(mobile_dirs)
+monotouch_SUBDIRS := $(mobile_dirs) $(monotouch_dirs)
 monotouch_runtime_SUBDIRS := $(monotouch_runtime_dirs)
 mobile_static_SUBDIRS := $(mobile_dirs)
 mobile_SUBDIRS := $(mobile_dirs)
-net_3_5_SUBDIRS := $(net_3_5_only_dirs)
-net_4_0_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_4_0_dirs) $(net_4_0_only_dirs)
-net_4_5_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_4_0_dirs) $(net_4_5_dirs) aot-compiler
+xammac_SUBDIRS := $(mobile_dirs) $(xammac_dirs)
+net_3_5_SUBDIRS := $(xbuild_2_0_dirs)
+net_4_0_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_4_0_dirs) $(net_4_0_only_dirs) $(xbuild_4_0_dirs)
+net_4_5_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_4_0_dirs) $(net_4_5_dirs) $(xbuild_4_0_dirs) aot-compiler
+xbuild_12_SUBDIRS := $(xbuild_4_0_dirs)
 
 include ../build/rules.make
 
-SUBDIRS = $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs) $(net_3_5_only_dirs) $(mobile_dirs) $(net_4_0_dirs) $(net_4_0_only_dirs) $(net_4_5_dirs)
+SUBDIRS = $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs) $(mobile_dirs) $(monotouch_dirs) $(net_4_0_dirs) $(net_4_0_only_dirs) $(net_4_5_dirs)
 
-DIST_ONLY_SUBDIRS = dlr aot-compiler
+DIST_ONLY_SUBDIRS = dlr aot-compiler $(xbuild_dirs)
 
 # No new makefiles for: System.Messaging, System.Web.Mobile,
 # System.ServiceProcess
index 71e5f4207c888601bb5fc7ed4eb7d8a1cd37104b..0452c2c6fa30f98c9ddc59221d008d5d545a805f 100644 (file)
@@ -2444,6 +2444,8 @@ namespace System.Windows.Forms {
 
                                if (selection_visible == false) {
                                        SetSelectionToCaret (true);
+                                       move_sel_start = false;
+                                       move_sel_end = false;
                                }
                        }
 
index 9c51bc96e5d33618b55b0e3cce708afd5f06a0a5..52cbf310891daa7c1124bb8fcceb2bab2214cfd6 100644 (file)
@@ -44,9 +44,9 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyCompany (Consts.MonoCompany)]
 [assembly: AssemblyProduct (Consts.MonoProduct)]
 [assembly: AssemblyCopyright (Consts.MonoCopyright)]
-[assembly: AssemblyVersion (Consts.FxVersion)]
-[assembly: SatelliteContractVersion (Consts.FxVersion)]
-[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyVersion (XBuildConsts.AssemblyVersion)]
+[assembly: SatelliteContractVersion (XBuildConsts.AssemblyVersion)]
+[assembly: AssemblyInformationalVersion (XBuildConsts.FileVersion)]
 
 [assembly: NeutralResourcesLanguage ("en-US")]
 
@@ -55,5 +55,5 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDelaySign (true)]
 [assembly: AssemblyKeyFile("../msfinal.pub")]
 
-[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (XBuildConsts.FileVersion)]
 
index 3bba6d640425376010384ff1bc9b2dae07dad94e..04f9e66dac5c2a9487a6869fc26e0fa10acf1b1d 100644 (file)
@@ -2,64 +2,38 @@ thisdir = class/Microsoft.Build.Engine
 SUBDIRS = 
 include ../../build/rules.make
 
-LIBRARY = Microsoft.Build.Engine.dll
-
-BUILD_FRAMEWORK = Microsoft.Build.Framework.dll
+XBUILD_DIR=$(topdir)/tools/xbuild
+include $(XBUILD_DIR)/xbuild.make
 
-ifeq (3.5, $(FRAMEWORK_VERSION))
-NAME_SUFFIX = .v3.5
-BUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/$(BUILD_FRAMEWORK)
-else
-ifeq (4, $(FRAMEWORK_VERSION_MAJOR))
-NAME_SUFFIX = .v4.0
-endif
-endif
+LIBRARY = Microsoft.Build.Engine.dll
 
 LIB_MCS_FLAGS = \
-       /r:$(corlib)                            \
-       /r:System.dll                           \
-       /r:System.Core.dll              \
-       /r:System.Xml.dll                       \
-       /r:$(BUILD_FRAMEWORK)                   \
-       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll
+       /r:$(corlib)            \
+       /r:System.dll           \
+       /r:System.Core.dll      \
+       /r:System.Xml.dll       \
+       /r:$(XBUILD_FRAMEWORK)  \
+       /r:$(XBUILD_UTILITIES)
 
 TEST_MCS_FLAGS = \
-       /r:$(BUILD_FRAMEWORK)   \
-       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll \
+       /r:$(XBUILD_FRAMEWORK)  \
+       /r:$(XBUILD_UTILITIES) \
        /r:System.Xml.dll
 
 EXTRA_DISTFILES = \
        Test/resources/TestTasks.cs             \
        Test/resources/*.*proj  \
-       Test/resources/*.csproj \
-       Test/test-config-file*
+       Test/resources/*.csproj
 
 Test/resources/TestTasks.dll: Test/resources/TestTasks.cs
-       $(CSCOMPILE) Test/resources/TestTasks.cs /r:Microsoft.Build.Framework.dll /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll /target:library
-
-clean-local: clean-test-tasks
+       $(CSCOMPILE) Test/resources/TestTasks.cs /r:$(XBUILD_FRAMEWORK) /r:$(XBUILD_UTILITIES) /target:library
 
-clean-test-tasks:
+clean-test-resources:
        rm -f Test/resources/TestTasks.dll      
 
-test-local: copy-config
-
-ifeq (net_4_0, $(PROFILE))
-copy-config:
-       cp Test/test-config-file-net-4.0 $(test_lib).config
-else
-ifeq (net_3_5, $(PROFILE))
-copy-config:
-       cp Test/test-config-file-net-3.5 $(test_lib).config
-else
-copy-config:
-endif
-endif
-
-export TESTING_MONO=a
-XBUILD_DIR=../../tools/xbuild
-include $(XBUILD_DIR)/xbuild_targets.make
-
 test-local: Test/resources/TestTasks.dll
 
+clean-local: clean-test-resources
+
+include $(XBUILD_DIR)/xbuild_test.make
 include ../../build/library.make
index fc22d1f56310b44b63bc5a3cf9858ef33f08be98..86f14a1a797af9fa3277bba8f7d5f61e0c361f30 100644 (file)
@@ -167,9 +167,7 @@ namespace Microsoft.Build.BuildEngine {
                {
                        if (ReservedNameUtils.IsReservedMetadataName (metadataName)) {
                                string metadata = ReservedNameUtils.GetReservedMetadata (FinalItemSpec, metadataName, evaluatedMetadata);
-                               return string.Equals (metadataName, "fullpath", StringComparison.OrdinalIgnoreCase)
-                                               ? MSBuildUtils.Escape (metadata)
-                                               : metadata;
+                               return MSBuildUtils.Unescape (metadata);
                        }
 
                        if (evaluatedMetadata.Contains (metadataName))
@@ -181,10 +179,7 @@ namespace Microsoft.Build.BuildEngine {
                public string GetMetadata (string metadataName)
                {
                        if (ReservedNameUtils.IsReservedMetadataName (metadataName)) {
-                               string metadata = ReservedNameUtils.GetReservedMetadata (FinalItemSpec, metadataName, unevaluatedMetadata);
-                               return string.Equals (metadataName, "fullpath", StringComparison.OrdinalIgnoreCase)
-                                       ? MSBuildUtils.Escape (metadata)
-                                       : metadata;
+                               return ReservedNameUtils.GetReservedMetadata (FinalItemSpec, metadataName, unevaluatedMetadata);
                        } else if (unevaluatedMetadata.Contains (metadataName))
                                return (string) unevaluatedMetadata [metadataName];
                        else
index 577a4379d291aeb102a47e97ecb2d288150222a4..cbb5fd6d05233d7831d971ecb1376b864f34cb23 100644 (file)
@@ -118,10 +118,8 @@ namespace Microsoft.Build.BuildEngine {
                        Toolsets.Add (new Toolset ("4.0",
                                                ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
 #endif
-#if NET_4_5
-                       Toolsets.Add (new Toolset("12.0",
-                                               ToolLocationHelper.GetMSBuildInstallPath ("12.0"),
-                                               ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
+#if XBUILD_12
+                       Toolsets.Add (new Toolset ("12.0", ToolLocationHelper.GetPathToBuildTools ("12.0")));
 #endif
                }
                
index d7edd5f29614b7c9ed6bde12149c1d7300d677a1..c22b8c749c916f44f4fecba2b1d3501143129ef4 100644 (file)
@@ -38,6 +38,7 @@ using System.Text;
 using System.Xml;
 using System.Xml.Schema;
 using Microsoft.Build.Framework;
+using Microsoft.Build.Utilities;
 using Mono.XBuild.Framework;
 using Mono.XBuild.CommandLine;
 
@@ -1032,13 +1033,13 @@ namespace Microsoft.Build.BuildEngine {
                        SetExtensionsPathProperties (DefaultExtensionsPath);
                        evaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
                        evaluatedProperties.AddProperty (new BuildProperty ("OS", OS, PropertyType.Environment));
-#if NET_4_5
+#if XBUILD_12
                        // see http://msdn.microsoft.com/en-us/library/vstudio/hh162058(v=vs.120).aspx
                        if (effective_tools_version == "12.0") {
                                evaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath32", toolsPath, PropertyType.Reserved));
-                               string frameworkToolsPath = parentEngine.Toolsets [effective_tools_version].FrameworkToolsPath;
-                               if (frameworkToolsPath == null)
-                                       throw new Exception (String.Format ("Invalid tools version '{0}', no framework tools path set for this.", effective_tools_version));                            
+
+                               var frameworkToolsPath = ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version451);
+
                                evaluatedProperties.AddProperty (new BuildProperty ("MSBuildFrameworkToolsPath", frameworkToolsPath, PropertyType.Reserved));
                                evaluatedProperties.AddProperty (new BuildProperty ("MSBuildFrameworkToolsPath32", frameworkToolsPath, PropertyType.Reserved));
                        }
index 0957f298c500fe263bdcda07fa25cbc0e5d32bd9..895bbeebf7a76d32e519be0b2e16bc4d82b7135c 100644 (file)
@@ -31,21 +31,15 @@ namespace Microsoft.Build.BuildEngine
 {
        public class Toolset
        {
-               public Toolset (string toolsVersion, string toolsPath, string toolsFrameworkPath, BuildPropertyGroup buildProperties)
+               public Toolset (string toolsVersion, string toolsPath, BuildPropertyGroup buildProperties)
                {
                        ToolsVersion = toolsVersion;
                        ToolsPath = toolsPath;
-                       FrameworkToolsPath = toolsFrameworkPath;
                        BuildProperties = buildProperties;
                }
 
-               public Toolset (string toolsVersion, string toolsPath, string toolsFrameworkPath)
-                       : this (toolsVersion, toolsPath, toolsFrameworkPath, null)
-               {
-               }
-
-               public Toolset(string toolsVersion, string toolsPath)
-                       : this (toolsVersion, toolsPath, toolsPath)
+               public Toolset (string toolsVersion, string toolsPath)
+                       : this (toolsVersion, toolsPath, null)
                {
                }
 
@@ -53,6 +47,5 @@ namespace Microsoft.Build.BuildEngine
 
                public string ToolsVersion { get; private set; }
                public string ToolsPath { get; private set; }
-               public string FrameworkToolsPath { get; private set; }          
        }
 }
index 9081b936b5da8b302def303583eaa962a4658bd4..3a9d701993630e5d1171ee4693ee7068014cdc45 100644 (file)
@@ -1,5 +1,6 @@
 ../../build/common/Consts.cs
 ../../build/common/MonoTODOAttribute.cs
+../../tools/xbuild/XBuildConsts.cs
 Assembly/AssemblyInfo.cs
 ../Microsoft.Build.Framework/Mono.XBuild.Framework/AssemblyLoadInfo.cs
 ../Microsoft.Build.Utilities/Mono.XBuild.Utilities/MSBuildUtils.cs
index e580d358ed07dd16235f4eec2c0bb939b4a91d12..918c3ff8ae2caf3ff89568300bf3ab53f3d3dc0b 100644 (file)
@@ -284,6 +284,40 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                        Assert.AreEqual (String.Empty, item.GetMetadata ("AccessedTime"), "A13");
                }
 
+               [Test]
+               public void GetMetadata_UnescapedItemSpec ()
+               {
+                       string itemInclude = "a;b;c";
+                       string escapedItemInclude = Utilities.Escape (itemInclude);
+
+                       item = new BuildItem ("name", itemInclude);
+                       Assert.IsTrue (item.GetMetadata ("FullPath").EndsWith (escapedItemInclude), "#1a");
+                       Assert.IsTrue (item.GetEvaluatedMetadata ("FullPath").EndsWith (itemInclude), "#1b");
+
+                       Assert.AreEqual (itemInclude, item.GetMetadata ("FileName"), "#2b");
+                       Assert.AreEqual (itemInclude, item.GetEvaluatedMetadata ("FileName"), "#2b");
+
+                       Assert.AreEqual (itemInclude, item.GetMetadata ("Identity"), "#3a");
+                       Assert.AreEqual (itemInclude, item.GetEvaluatedMetadata ("Identity"), "#3b");
+               }
+
+               [Test]
+               public void GetMetadata_EscapedItemSpec ()
+               {
+                       string itemInclude = "a;b;c";
+                       string escapedItemInclude = Utilities.Escape (itemInclude);
+
+                       item = new BuildItem ("name", escapedItemInclude);
+                       Assert.IsTrue (item.GetMetadata ("FullPath").EndsWith (escapedItemInclude), "#1a");
+                       Assert.IsTrue (item.GetEvaluatedMetadata ("FullPath").EndsWith (itemInclude), "#1b");
+
+                       Assert.AreEqual (escapedItemInclude, item.GetMetadata ("FileName"), "#2b");
+                       Assert.AreEqual (itemInclude, item.GetEvaluatedMetadata ("FileName"), "#2b");
+
+                       Assert.AreEqual (escapedItemInclude, item.GetMetadata ("Identity"), "#3a");
+                       Assert.AreEqual ("a;b;c", item.GetEvaluatedMetadata ("Identity"), "#3b");
+               }
+
                [Test]
                [ExpectedException (typeof (ArgumentNullException))]
                public void TestGetMetadata2 ()
index 31a160850a170cd7bbc08aaa2667bfddfd8078c2..8db3be70a9df673c0ef434dd73d96699152a3b57 100644 (file)
@@ -38,16 +38,42 @@ public static class Consts {
        
        public static string BinPath {
                get {
-                       if (RunningOnMono ())
-                               return "../../tools/xbuild/xbuild";
-                       else
+                       if (RunningOnMono ()) {
+#if XBUILD_12
+                               string profile = "xbuild_12";
+#elif NET_4_5
+                               string profile = "net_4_5";
+#elif NET_4_0
+                               string profile = "net_4_0";
+#elif NET_3_5
+                               string profile = "net_3_5";
+#else
+                               string profile = "net_2_0";
+#endif
+                               var corlib = typeof (object).Assembly.Location;
+                               var lib = Path.GetDirectoryName (Path.GetDirectoryName (corlib));
+                               return Path.Combine (lib, profile);
+                       } else {
+#if XBUILD_12
+                               return ToolLocationHelper.GetPathToBuildTools ("12.0");
+#elif NET_4_5
+                               return ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version45);
+#elif NET_4_0
+                               return ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40);
+#elif NET_3_5
+                               return ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35);
+#else
                                return ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20);
+#endif
+                       }
                }
        }
 
        public static string ToolsVersionString {
                get {
-#if NET_4_0
+#if XBUILD_12
+                       return " ToolsVersion='12.0'";
+#elif NET_4_0
                        return " ToolsVersion='4.0'";
 #elif NET_3_5
                        return " ToolsVersion='3.5'";
@@ -59,12 +85,14 @@ public static class Consts {
 
        public static string GetTasksAsmPath ()
        {
-#if NET_4_0
-               return Path.Combine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40), "Microsoft.Build.Tasks.v4.0.dll");
+#if XBUILD_12
+               return Path.Combine (BinPath, "Microsoft.Build.Tasks.v12.0.dll");
+#elif NET_4_0
+               return Path.Combine (BinPath, "Microsoft.Build.Tasks.v4.0.dll");
 #elif NET_3_5
-               return Path.Combine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35), "Microsoft.Build.Tasks.v3.5.dll");
+               return Path.Combine (BinPath, "Microsoft.Build.Tasks.v3.5.dll");
 #else
-               return Path.Combine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20), "Microsoft.Build.Tasks.dll");
+               return Path.Combine (BinPath, "Microsoft.Build.Tasks.dll");
 #endif
        }
 }
diff --git a/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-3.5 b/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-3.5
deleted file mode 100644 (file)
index 7756bca..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version ="1.0"?>
-<configuration>
-    <runtime>
-        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
-            <dependentAssembly>
-                <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
-                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
-            </dependentAssembly>
-            <dependentAssembly>
-                <assemblyIdentity name="Microsoft.Build.Engine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
-                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
-            </dependentAssembly>
-        </assemblyBinding>
-    </runtime>
-</configuration>
diff --git a/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-4.0 b/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-4.0
deleted file mode 100644 (file)
index 3c78f3b..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version ="1.0"?>
-<configuration>
-    <runtime>
-        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
-            <dependentAssembly>
-                <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
-                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="4.0.0.0"/>
-            </dependentAssembly>
-            <dependentAssembly>
-                <assemblyIdentity name="Microsoft.Build.Engine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
-                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="4.0.0.0"/>
-            </dependentAssembly>
-        </assemblyBinding>
-    </runtime>
-</configuration>
index 1c7777bfa7997dbdbf715f66256db67decc9c74a..2110fd06684c2117966507955dd17d6dcca8af40 100644 (file)
@@ -44,9 +44,9 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyCompany (Consts.MonoCompany)]
 [assembly: AssemblyProduct (Consts.MonoProduct)]
 [assembly: AssemblyCopyright (Consts.MonoCopyright)]
-[assembly: AssemblyVersion (Consts.FxVersion)]
-[assembly: SatelliteContractVersion (Consts.FxVersion)]
-[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyVersion (XBuildConsts.AssemblyVersion)]
+[assembly: SatelliteContractVersion (XBuildConsts.AssemblyVersion)]
+[assembly: AssemblyInformationalVersion (XBuildConsts.FileVersion)]
 
 [assembly: NeutralResourcesLanguage ("en-US")]
 
@@ -56,5 +56,5 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDelaySign (true)]
 [assembly: AssemblyKeyFile("../msfinal.pub")]
 
-[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (XBuildConsts.FileVersion)]
 
index 0cb68bfac6cd19c1a3e79e764060f67ea43dbd21..73f43fb74c773eab3c4c6617c6f2c3c6ede45f52 100644 (file)
@@ -2,24 +2,17 @@ thisdir = class/Microsoft.Build.Framework
 SUBDIRS = 
 include ../../build/rules.make
 
-LIBRARY = Microsoft.Build.Framework.dll
+XBUILD_DIR=$(topdir)/tools/xbuild
+include $(XBUILD_DIR)/xbuild.make
 
-ifeq (1.0, $(FRAMEWORK_VERSION))
-LIBRARY_NAME = dummy-Microsoft.Build.Framework.dll
-NO_INSTALL = yes
-NO_TEST = yes
-NO_SIGN_ASSEMBLY = yes
-endif
+LIBRARY = Microsoft.Build.Framework.dll
 
 LIB_MCS_FLAGS = \
        /r:$(corlib)                            \
        /r:System.dll
 
-include ../../build/library.make
-
-export TESTING_MONO=a
-XBUILD_DIR=../../tools/xbuild
-include $(XBUILD_DIR)/xbuild_targets.make
-
 EXTRA_DISTFILES = \
        Mono.XBuild.Framework/AssemblyLoadInfo.cs
+
+include ../../build/library.make
+include $(XBUILD_DIR)/xbuild_test.make
index d24bf602ad312d6d77f7dc9feef2a67b290f7c2e..bb3c1d6d07d6c5ad0cfaf7de367d173213df352b 100644 (file)
@@ -1,5 +1,6 @@
 ../../build/common/Consts.cs
 ../../build/common/MonoTODOAttribute.cs
+../../tools/xbuild/XBuildConsts.cs
 Assembly/AssemblyInfo.cs
 Microsoft.Build.Framework/AnyEventHandler.cs
 Microsoft.Build.Framework/BuildEngineResult.cs
index 25dc0b7ec1615b020a4a3712451e5e58debead43..172f71e95b97159af3a98418cf69032965ad7514 100644 (file)
@@ -44,9 +44,9 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyCompany (Consts.MonoCompany)]
 [assembly: AssemblyProduct (Consts.MonoProduct)]
 [assembly: AssemblyCopyright (Consts.MonoCopyright)]
-[assembly: AssemblyVersion (Consts.FxVersion)]
-[assembly: SatelliteContractVersion (Consts.FxVersion)]
-[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyVersion (XBuildConsts.AssemblyVersion)]
+[assembly: SatelliteContractVersion (XBuildConsts.AssemblyVersion)]
+[assembly: AssemblyInformationalVersion (XBuildConsts.FileVersion)]
 
 [assembly: NeutralResourcesLanguage ("en-US")]
 
@@ -56,4 +56,4 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDelaySign (true)]
 [assembly: AssemblyKeyFile("../msfinal.pub")]
 
-[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (XBuildConsts.FileVersion)]
index 4161a45b51cb2134b7443ffd3ce69a194c7fdba3..d8e93372f455a7ed6d829a1ae0b9c51a3e9906c7 100644 (file)
@@ -1,25 +1,11 @@
 thisdir = class/Microsoft.Build.Tasks
-SUBDIRS = 
+SUBDIRS =
 include ../../build/rules.make
 
-LIBRARY = Microsoft.Build.Tasks.dll
-BUILD_FRAMEWORK = Microsoft.Build.Framework.dll
-BUILD_ENGINE = Microsoft.Build.Engine.dll
-XBUILD_TASKS = Mono.XBuild.Tasks.dll
-
-ifeq (3.5, $(FRAMEWORK_VERSION))
-NAME_SUFFIX = .v3.5
-BUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/$(BUILD_FRAMEWORK)
-BUILD_ENGINE := $(topdir)/class/lib/$(PROFILE)/$(BUILD_ENGINE)
-XBUILD_TASKS := $(topdir)/class/lib/$(PROFILE)/$(XBUILD_TASKS)
-else
-ifeq (4, $(FRAMEWORK_VERSION_MAJOR))
-NAME_SUFFIX = .v4.0
-endif
-endif
+XBUILD_DIR=$(topdir)/tools/xbuild
+include $(XBUILD_DIR)/xbuild.make
 
-# Some tests are explicitly testing Microsoft.Build.Tasks.v3.5.dll
-TEST_MONO_PATH = $(topdir)/class/lib/net_3_5$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/net_2_0
+LIBRARY = Microsoft.Build.Tasks.dll
 
 LIBRARY_NAME = Microsoft.Build.Tasks$(NAME_SUFFIX).dll
 
@@ -29,16 +15,16 @@ LIB_MCS_FLAGS = \
        /r:System.Core.dll                      \
        /r:System.Xml.dll                       \
        /r:System.Windows.Forms.dll             \
-       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll  \
-       /r:$(BUILD_FRAMEWORK)   \
-       /r:$(BUILD_ENGINE)              \
+       /r:$(XBUILD_UTILITIES)                  \
+       /r:$(XBUILD_FRAMEWORK)                  \
+       /r:$(XBUILD_ENGINE)                     \
        /r:$(XBUILD_TASKS)
 
 TEST_MCS_FLAGS = \
-       /r:$(BUILD_ENGINE)      \
-       /r:$(BUILD_FRAMEWORK)   \
-       /r:$(XBUILD_TASKS)              \
-       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll \
+       /r:$(XBUILD_ENGINE)     \
+       /r:$(XBUILD_FRAMEWORK)  \
+       /r:$(XBUILD_TASKS)      \
+       /r:$(XBUILD_UTILITIES)                  \
        /r:System.Core.dll
 
 EXTRA_DISTFILES = \
@@ -48,37 +34,15 @@ EXTRA_DISTFILES = \
        Test/resources/junk.txt \
        Test/test-config-file*
 
-test-local: Test/resources/test.dll
-
 Test/resources/test.dll: Test/resources/test.cs
        $(CSCOMPILE) -target:library Test/resources/test.cs
 
-clean-local: clean-test-dll
-
-clean-test-dll:
+clean-test-resources:
        rm -f Test/resources/test.dll
 
-test-local: copy-config
-
-ifeq (net_4_5, $(PROFILE))
-copy-config:
-       cp Test/test-config-file-net-4.0 $(test_lib).config
-else
-ifeq (net_4_0, $(PROFILE))
-copy-config:
-       cp Test/test-config-file-net-4.0 $(test_lib).config
-else
-ifeq (net_3_5, $(PROFILE))
-copy-config:
-       cp Test/test-config-file-net-3.5 $(test_lib).config
-else
-copy-config:
-endif
-endif
-endif
+test-local: Test/resources/test.dll
 
-export TESTING_MONO=a
-XBUILD_DIR=../../tools/xbuild
-include $(XBUILD_DIR)/xbuild_targets.make
+clean-local: clean-test-resources
 
+include $(XBUILD_DIR)/xbuild_test.make
 include ../../build/library.make
index e61c90c6300a94d142169618f4124eb64eab0144..6785e5ef882b0735cc4a798c6521498097764701 100644 (file)
@@ -1,6 +1,7 @@
 Assembly/AssemblyInfo.cs
 ../../build/common/Consts.cs
 ../../build/common/MonoTODOAttribute.cs
+../../tools/xbuild/XBuildConsts.cs
 Microsoft.Build.Tasks/AL.cs
 Microsoft.Build.Tasks/AppDomainIsolatedTaskExtension.cs
 Microsoft.Build.Tasks/AspNetCompiler.cs
index 90933c5a29fd49a00c7da1863852a5750009e2a3..2f80ed7552e0b011dd4e98875c0437abc16a364f 100644 (file)
@@ -46,9 +46,9 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyCompany (Consts.MonoCompany)]
 [assembly: AssemblyProduct (Consts.MonoProduct)]
 [assembly: AssemblyCopyright (Consts.MonoCopyright)]
-[assembly: AssemblyVersion (Consts.FxVersion)]
-[assembly: SatelliteContractVersion (Consts.FxVersion)]
-[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyVersion (XBuildConsts.AssemblyVersion)]
+[assembly: SatelliteContractVersion (XBuildConsts.AssemblyVersion)]
+[assembly: AssemblyInformationalVersion (XBuildConsts.FileVersion)]
 
 [assembly: NeutralResourcesLanguage ("en-US")]
 
@@ -57,6 +57,6 @@ using System.Runtime.InteropServices;
 [assembly: AssemblyDelaySign (true)]
 [assembly: AssemblyKeyFile("../msfinal.pub")]
 
-[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (XBuildConsts.FileVersion)]
 
 #endif
index 585e5bb0a4f3e0eff7b65d00b3d29fdfec61a96c..79888a2a3b4491391527253aa3414c3178094379 100644 (file)
@@ -2,27 +2,18 @@ thisdir = class/Microsoft.Build.Utilities
 SUBDIRS = 
 include ../../build/rules.make
 
-LIBRARY = Microsoft.Build.Utilities.dll
-BUILD_FRAMEWORK = Microsoft.Build.Framework.dll
+XBUILD_DIR=$(topdir)/tools/xbuild
+include $(XBUILD_DIR)/xbuild.make
 
-ifeq (3.5, $(FRAMEWORK_VERSION))
-LIBRARY_NAME = Microsoft.Build.Utilities.v3.5.dll
-BUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/$(BUILD_FRAMEWORK)
-else
-ifeq (4, $(FRAMEWORK_VERSION_MAJOR))
-LIBRARY_NAME = Microsoft.Build.Utilities.v4.0.dll
-endif
-endif
+LIBRARY = Microsoft.Build.Utilities.dll
+LIBRARY_NAME = Microsoft.Build.Utilities$(NAME_SUFFIX).dll
 
 LIB_MCS_FLAGS = \
        /r:$(corlib)                            \
        /r:System.dll                           \
-       /r:$(BUILD_FRAMEWORK)
-
-TEST_MCS_FLAGS = /r:$(BUILD_FRAMEWORK) -r:System.dll -r:System.Core.dll
+       /r:$(XBUILD_FRAMEWORK)
 
-export TESTING_MONO=a
-XBUILD_DIR=../../tools/xbuild
-include $(XBUILD_DIR)/xbuild_targets.make
+TEST_MCS_FLAGS = /r:$(XBUILD_FRAMEWORK) -r:System.dll -r:System.Core.dll
 
+include $(XBUILD_DIR)/xbuild_test.make
 include ../../build/library.make
index c37728258680873f1188a7f8e71b063b13208636..deb3e77ec93a3b8bc59e14a898d2a2b083983bda 100644 (file)
@@ -1,5 +1,6 @@
 ../../build/common/Consts.cs
 ../../build/common/MonoTODOAttribute.cs
+../../tools/xbuild/XBuildConsts.cs
 Assembly/AssemblyInfo.cs
 Microsoft.Build.Utilities/AppDomainIsolatedTask.cs
 Microsoft.Build.Utilities/CommandLineBuilder.cs
index 3de49797724445ed39a605db3e25215d4049b7d3..d022ea16c01458f5a1209dadb04d7215921e1221 100644 (file)
@@ -117,6 +117,7 @@ namespace Microsoft.Build.Utilities
                        startInfo.RedirectStandardError = true;
                        startInfo.RedirectStandardInput = redirectStandardInput;
                        startInfo.UseShellExecute = false;
+                       startInfo.CreateNoWindow = true;
 
                        return startInfo;
                }
index 0906ef3ebf5cda566ecd857f35a602276fa27777..04940d5e8badbdce51fbf6219c40685962021d7d 100644 (file)
@@ -48,8 +48,13 @@ namespace Microsoft.Build.Utilities
 #if NET_4_5
                Version45,
 #endif
+#if XBUILD_12
+               Version451,
+#endif
 
-#if NET_4_5
+#if XBUILD_12
+               VersionLatest = Version451
+#elif NET_4_5
                VersionLatest = Version45
 #elif NET_4_0
                VersionLatest = Version40
index e61094bc8676f7ee479fd91c7563ec7983308d4a..91441df066993862fa4100538be7fc25ce6c2e22 100644 (file)
@@ -39,6 +39,7 @@ namespace Microsoft.Build.Utilities
        {
                static string lib_mono_dir;
                static string [] mono_dir;
+               static bool runningOnDotNet;
 
                static ToolLocationHelper ()
                {
@@ -53,38 +54,45 @@ namespace Microsoft.Build.Utilities
                        t2 = t1.Parent;
 
                        lib_mono_dir = t2.FullName;
+
 #if NET_4_0
                        var windowsPath = Environment.GetFolderPath (Environment.SpecialFolder.Windows);
+                       runningOnDotNet = !string.IsNullOrEmpty (windowsPath) && lib_mono_dir.StartsWith (windowsPath);
 #endif
+
                        if (Environment.GetEnvironmentVariable ("TESTING_MONO") != null) {
                                mono_dir = new string [] {
                                        Path.Combine (lib_mono_dir, "net_1_0"),
                                        Path.Combine (lib_mono_dir, "net_2_0"),
                                        Path.Combine (lib_mono_dir, "net_2_0"),
                                        Path.Combine (lib_mono_dir, "net_3_5"),
-                                       Path.Combine (lib_mono_dir, "net_4_0"),
+                                       // mono's 4.0 is not an actual framework directory with all tools etc
+                                       // it's simply reference assemblies. So like .NET we consider 4.5 to
+                                       // be a complete replacement for 4.0.
+                                       Path.Combine (lib_mono_dir, "net_4_5"),
+                                       Path.Combine (lib_mono_dir, "net_4_5"),
                                        Path.Combine (lib_mono_dir, "net_4_5")
                                };      
-#if NET_4_0
-                       } else if (!string.IsNullOrEmpty (windowsPath) && lib_mono_dir.StartsWith (windowsPath)) {
-                               //running in .NET, not Mono
+                       } else if (runningOnDotNet) {
                                mono_dir = new string [] {
                                        Path.Combine (lib_mono_dir, "v1.0.3705"),
                                        Path.Combine (lib_mono_dir, "v2.0.50727"),
                                        Path.Combine (lib_mono_dir, "v2.0.50727"),
                                        Path.Combine (lib_mono_dir, "v3.5"),
                                        Path.Combine (lib_mono_dir, "v4.0.30319"),
+                                       Path.Combine (lib_mono_dir, "v4.0.30319"),
                                        Path.Combine (lib_mono_dir, "v4.0.30319")
                                };
-#endif
                        } else {
                                mono_dir = new string [] {
                                        Path.Combine (lib_mono_dir, "1.0"),
                                        Path.Combine (lib_mono_dir, "2.0"),
                                        Path.Combine (lib_mono_dir, "2.0"),
                                        Path.Combine (lib_mono_dir, "3.5"),
-                                       Path.Combine (lib_mono_dir, "4.0"),
-                                       Path.Combine (lib_mono_dir, "4.5")
+                                       // see comment above regarding 4.0/4.5
+                                       Path.Combine (lib_mono_dir, "4.5"),
+                                       Path.Combine (lib_mono_dir, "4.5"),
+                                       Path.Combine (lib_mono_dir, "4.5"),
                                };
                        }
 
@@ -113,15 +121,6 @@ namespace Microsoft.Build.Utilities
                        return mono_dir [(int)version];
                }
 
-#if NET_4_0
-               public static string GetMSBuildInstallPath (string version)
-               {
-                       //see http://msdn.microsoft.com/en-us/library/vstudio/bb397428(v=vs.120).aspx
-                       var programFiles = Environment.GetFolderPath (Environment.SpecialFolder.ProgramFilesX86);
-                       return Path.Combine (programFiles, "MSBuild", version, "bin");
-               }
-#endif
-
                [MonoTODO]
                public static string GetPathToDotNetFrameworkFile (string fileName,
                                                                  TargetDotNetFrameworkVersion version)
@@ -153,5 +152,30 @@ namespace Microsoft.Build.Utilities
                                throw new NotImplementedException ();
                        }
                }
+
+#if XBUILD_12
+               public static string CurrentToolsVersion {
+                       get {
+                               return XBuildConsts.Version;
+                       }
+               }
+
+               public static string GetPathToBuildTools (string toolsVersion)
+               {
+                       if (toolsVersion != "12.0")
+                               return null;
+
+                       if (Environment.GetEnvironmentVariable ("TESTING_MONO") != null)
+                               return Path.Combine (lib_mono_dir, "xbuild_12");
+
+                       if (runningOnDotNet) {
+                               //see http://msdn.microsoft.com/en-us/library/vstudio/bb397428(v=vs.120).aspx
+                               var programFiles = Environment.GetFolderPath (Environment.SpecialFolder.ProgramFilesX86);
+                               return Path.Combine (programFiles, "MSBuild", toolsVersion, "bin");
+                       }
+
+                       return Path.Combine (lib_mono_dir, "xbuild", toolsVersion, "bin");
+               }
+#endif
        }
 }
index 77814aab8621b327e16c0e952105454ac32dd66b..01a7c453aeca02c8be1da294dbd41d71dac98b60 100644 (file)
@@ -298,6 +298,7 @@ namespace Microsoft.Build.Utilities
 
                        pinfo.WorkingDirectory = GetWorkingDirectory () ?? Environment.CurrentDirectory;
                        pinfo.UseShellExecute = false;
+                       pinfo.CreateNoWindow = true;
                        pinfo.RedirectStandardOutput = true;
                        pinfo.RedirectStandardError = true;
 
index f2712566d594d5fca282c6c2765ad57f4d6e8da1..6789cfbd9283a577f38482fde1387b546529dc8d 100644 (file)
@@ -77,7 +77,8 @@ namespace Mono.XBuild.Utilities {
                
                        switch (metadataName.ToLowerInvariant ()) {
                        case "fullpath":
-                               return Path.GetFullPath (itemSpec);
+                               var unescapedItemSpec = MSBuildUtils.Unescape (itemSpec);
+                               return MSBuildUtils.Escape (Path.GetFullPath (unescapedItemSpec));
                        case "rootdir":
                                if (Path.IsPathRooted (itemSpec))
                                        return Path.GetPathRoot (itemSpec);
index edc155a8afb5714439caf8ee26d57bda3abbab0b..e14ad00346ba08c4fba2f5724d6d3252a6f85758 100644 (file)
@@ -46,9 +46,9 @@ using System.Runtime.Versioning;
 [assembly: AssemblyCompany (Consts.MonoCompany)]
 [assembly: AssemblyProduct (Consts.MonoProduct)]
 [assembly: AssemblyCopyright (Consts.MonoCopyright)]
-[assembly: AssemblyVersion (Consts.FxVersion)]
-[assembly: SatelliteContractVersion (Consts.FxVersion)]
-[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyVersion (XBuildConsts.AssemblyVersion)]
+[assembly: SatelliteContractVersion (XBuildConsts.AssemblyVersion)]
+[assembly: AssemblyInformationalVersion (XBuildConsts.FileVersion)]
 
 [assembly: NeutralResourcesLanguage ("en-US")]
 
@@ -57,6 +57,6 @@ using System.Runtime.Versioning;
 [assembly: AssemblyDelaySign (true)]
 [assembly: AssemblyKeyFile("../msfinal.pub")]
 
-[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (XBuildConsts.FileVersion)]
 [assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
 
index f41641208cc7aa697cd516c7564673b8c11eec36..931b9fc7e57482e278392af95aabd5ab397d55c8 100644 (file)
@@ -2,14 +2,10 @@ thisdir = class/Microsoft.Build
 SUBDIRS = 
 include ../../build/rules.make
 
-LIBRARY = Microsoft.Build.dll
+XBUILD_DIR=$(topdir)/tools/xbuild
+include $(XBUILD_DIR)/xbuild.make
 
-ifneq (4, $(FRAMEWORK_VERSION_MAJOR))
-LIBRARY_NAME = dummy-Microsoft.Build.dll
-NO_INSTALL = yes
-NO_TEST = yes
-NO_SIGN_ASSEMBLY = yes
-endif
+LIBRARY = Microsoft.Build.dll
 
 LIB_MCS_FLAGS = \
        /r:$(corlib)                            \
@@ -38,7 +34,5 @@ BUILT_SOURCES = $(EXPR_PARSER).cs
 
 include ../../build/library.make
 
-export TESTING_MONO=a
-XBUILD_DIR=../../tools/xbuild
 XBUILD_FRAMEWORK_FOLDERS_PATH=xbuild-testing
-include $(XBUILD_DIR)/xbuild_targets.make
+include $(XBUILD_DIR)/xbuild_test.make
index 0c3d226fcd3ea5b48901cbd6f74746fcef8ad2c5..ab3ee06638909f6d645195d96d662e817cb55271 100644 (file)
@@ -259,9 +259,8 @@ namespace Microsoft.Build.Evaluation
                        AddToolset (new Toolset ("4.0",
                                ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40), this, null));
 #endif
-#if NET_4_5
-                       AddToolset (new Toolset ("12.0",
-                               ToolLocationHelper.GetMSBuildInstallPath ("12.0"), this, ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
+#if XBUILD_12
+                       AddToolset (new Toolset ("12.0", ToolLocationHelper.GetPathToBuildTools ("12.0"), this, null));
 #endif
                        default_tools_version = toolsets.First ().ToolsVersion;
                }
index 56d864cac2761cf02364bf1cfe587b13bafe56fa..6cbed8f392be7953011b98977a8cd386c350879d 100644 (file)
@@ -1,6 +1,7 @@
 Assembly/AssemblyInfo.cs
 ../../build/common/Consts.cs
 ../../build/common/MonoTODOAttribute.cs
+../../tools/xbuild/XBuildConsts.cs
 ../Microsoft.Build.Engine/Microsoft.Build.BuildEngine/DirectoryScanner.cs
 ../Microsoft.Build.Engine/Microsoft.Build.BuildEngine/EventSource.cs
 ../Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ColorSetter.cs
index 2e67f5993926e04edda39a0b1f555dc5eed9439d..85b86e0f4669a7666d8dec465e61e42cdecc9180 100644 (file)
@@ -6,6 +6,10 @@ LIBRARY = Mono.CSharp.dll
 
 LIB_MCS_FLAGS = -r:System.Core.dll -r:System.Xml.dll -r:System.dll
 
+ifeq (monotouch, $(PROFILE))
+LIB_MCS_FLAGS += -d:IOS_REFLECTION
+endif
+
 TEST_MCS_FLAGS = -r:System.Core.dll
 
 include ../../build/library.make
diff --git a/mcs/class/Mono.CSharp/monotouch.cs b/mcs/class/Mono.CSharp/monotouch.cs
new file mode 100644 (file)
index 0000000..fed1475
--- /dev/null
@@ -0,0 +1,1123 @@
+//
+// monotouch.cs: iOS System.Reflection.Emit API needed to simplify mcs compilation
+//
+// Authors:
+//     Marek Safar  <marek.safar@gmail.com>
+//
+// Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com)
+//
+// 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.
+//
+
+namespace System.Reflection.Emit
+{
+       public class ILGenerator
+       {
+               public void BeginCatchBlock (Type exceptionType)                
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public Label BeginExceptionBlock ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void BeginFinallyBlock ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public LocalBuilder DeclareLocal (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public Label DefineLabel ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void Emit (OpCode opcode)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void Emit (OpCode opcode, object args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public  void EmitCall (OpCode opcode, params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void EndExceptionBlock ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void MarkLabel (Label loc)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public int ILOffset { get; set; }
+       }
+
+       public class TypeBuilder : Type
+       {
+               #region implemented abstract members of MemberInfo
+
+               public override bool IsDefined (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override string Name {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               #region implemented abstract members of Type
+
+               public override Type GetInterface (string name, bool ignoreCase)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type[] GetInterfaces ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type GetElementType ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override EventInfo[] GetEvents (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FieldInfo GetField (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FieldInfo[] GetFields (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type GetNestedType (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type[] GetNestedTypes (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override TypeAttributes GetAttributeFlagsImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool HasElementTypeImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsArrayImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsByRefImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsCOMObjectImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsPointerImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsPrimitiveImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Assembly Assembly {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string AssemblyQualifiedName {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type BaseType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string FullName {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Guid GUID {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Module Module {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string Namespace {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type UnderlyingSystemType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               public void AddInterfaceImplementation (Type interfaceType)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void AddDeclarativeSecurity (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }       
+
+               public void SetParent (object arg)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public Type CreateType()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public ConstructorBuilder DefineConstructor (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public MethodBuilder DefineMethod (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public TypeBuilder DefineNestedType (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public PropertyBuilder DefineProperty (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public EventBuilder DefineEvent (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public FieldBuilder DefineField (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public MethodBuilder DefineMethodOverride (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public static ConstructorInfo GetConstructor (Type type, ConstructorInfo constructor)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public static FieldInfo GetField (Type type, FieldInfo field)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public static MethodInfo GetMethod (Type type, MethodInfo method)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class MethodBuilder : MethodBase
+       {
+               #region implemented abstract members of MemberInfo
+
+               public override bool IsDefined (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type DeclaringType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override MemberTypes MemberType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type ReflectedType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               #region implemented abstract members of MethodBase
+
+               public override MethodImplAttributes GetMethodImplementationFlags ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override ParameterInfo[] GetParameters ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, System.Globalization.CultureInfo culture)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override RuntimeMethodHandle MethodHandle {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override MethodAttributes Attributes {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               public void AddDeclarativeSecurity (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public ParameterBuilder DefineParameter (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public MethodToken GetToken()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public ILGenerator GetILGenerator ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetImplementationFlags (MethodImplAttributes attributes)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetParameters (params Type[] parameterTypes)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetReturnType (object arg)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class AssemblyBuilder : Assembly
+       {
+               public void AddResourceFile (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void DefineVersionInfoResource (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public ModuleBuilder DefineDynamicModule (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void DefineUnmanagedResource (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void Save (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetEntryPoint (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class LocalBuilder : LocalVariableInfo
+       {       
+       }
+
+       public class GenericTypeParameterBuilder : Type
+       {
+               #region implemented abstract members of MemberInfo
+
+               public override bool IsDefined (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override string Name {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               #region implemented abstract members of Type
+
+               public override Type GetInterface (string name, bool ignoreCase)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type[] GetInterfaces ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type GetElementType ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override EventInfo[] GetEvents (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FieldInfo GetField (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FieldInfo[] GetFields (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type GetNestedType (string name, BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type[] GetNestedTypes (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override TypeAttributes GetAttributeFlagsImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool HasElementTypeImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsArrayImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsByRefImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsCOMObjectImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsPointerImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               protected override bool IsPrimitiveImpl ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Assembly Assembly {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string AssemblyQualifiedName {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type BaseType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string FullName {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Guid GUID {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Module Module {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string Namespace {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type UnderlyingSystemType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetGenericParameterAttributes (GenericParameterAttributes genericParameterAttributes)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetInterfaceConstraints (params Type[] interfaceConstraints)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetBaseTypeConstraint (Type baseTypeConstraint)
+               {
+                       throw new NotSupportedException ();
+               }               
+       }
+
+       public class ConstructorBuilder : MethodBase
+       {
+               #region implemented abstract members of MemberInfo
+
+               public override bool IsDefined (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type DeclaringType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override MemberTypes MemberType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type ReflectedType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               #region implemented abstract members of MethodBase
+
+               public override MethodImplAttributes GetMethodImplementationFlags ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override ParameterInfo[] GetParameters ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, System.Globalization.CultureInfo culture)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override RuntimeMethodHandle MethodHandle {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override MethodAttributes Attributes {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               public void AddDeclarativeSecurity (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public ParameterBuilder DefineParameter (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }               
+
+               public MethodToken GetToken()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public ILGenerator GetILGenerator ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetImplementationFlags (MethodImplAttributes attributes)
+               {
+                       throw new NotSupportedException ();
+               }       
+       }
+
+       public class ModuleBuilder : Module
+       {
+               public void DefineManifestResource (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public TypeBuilder DefineType (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public MethodToken GetToken()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public MethodInfo GetArrayMethod (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class PropertyBuilder : PropertyInfo
+       {
+               #region implemented abstract members of MemberInfo
+
+               public override bool IsDefined (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type DeclaringType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type ReflectedType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               #region implemented abstract members of PropertyInfo
+
+               public override MethodInfo[] GetAccessors (bool nonPublic)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override MethodInfo GetGetMethod (bool nonPublic)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override ParameterInfo[] GetIndexParameters ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override MethodInfo GetSetMethod (bool nonPublic)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object GetValue (object obj, BindingFlags invokeAttr, Binder binder, object[] index, System.Globalization.CultureInfo culture)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, System.Globalization.CultureInfo culture)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override PropertyAttributes Attributes {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override bool CanRead {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override bool CanWrite {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type PropertyType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               public MethodToken GetToken()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetGetMethod (object arg)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetSetMethod (object arg)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class FieldBuilder : FieldInfo
+       {
+               #region implemented abstract members of MemberInfo
+
+               public override bool IsDefined (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override Type DeclaringType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type ReflectedType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               #region implemented abstract members of FieldInfo
+
+               public override object GetValue (object obj)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override void SetValue (object obj, object value, BindingFlags invokeAttr, Binder binder, System.Globalization.CultureInfo culture)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FieldAttributes Attributes {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override RuntimeFieldHandle FieldHandle {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               public override Type FieldType {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               public void SetConstant (object arg)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class ParameterBuilder : ParameterInfo
+       {
+               public void SetConstant (object arg)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class EventBuilder
+       {
+               public void SetAddOnMethod (MethodBuilder mdBuilder)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetRemoveOnMethod (MethodBuilder mdBuilder)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public void SetCustomAttribute (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+
+       public class CustomAttributeBuilder
+       {
+               public CustomAttributeBuilder (params object[] args)
+               {
+                       throw new NotSupportedException ();
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/Mono.CSharp/monotouch_Mono.CSharp.dll.sources b/mcs/class/Mono.CSharp/monotouch_Mono.CSharp.dll.sources
new file mode 100644 (file)
index 0000000..bebb2c0
--- /dev/null
@@ -0,0 +1,13 @@
+#include Mono.CSharp.dll.sources
+../corlib/System.Reflection.Emit/AssemblyBuilderAccess.cs
+../corlib/System.Reflection.Emit/FlowControl.cs
+../corlib/System.Reflection.Emit/Opcode.cs
+../corlib/System.Reflection.Emit/OpcodeNames.cs
+../corlib/System.Reflection.Emit/Opcodes.cs
+../corlib/System.Reflection.Emit/OpcodeType.cs
+../corlib/System.Reflection.Emit/OperandType.cs
+../corlib/System.Reflection.Emit/PEFileKinds.cs
+../corlib/System.Reflection.Emit/Label.cs
+../corlib/System.Reflection.Emit/MethodToken.cs
+../corlib/System.Reflection.Emit/StackBehaviour.cs
+monotouch.cs
\ No newline at end of file
index 1db6037972d5e0f0bd13bbb0b326fdf824780fa7..7307b0ea897db0868a10d743e47e061835ef84fc 100644 (file)
@@ -41,6 +41,20 @@ namespace Mono.Debugger.Soft
                                }
                                throw new ArgumentException ("Unknown struct field '" + field + "'.", "field");
                        }
+                       set {
+                               FieldInfoMirror[] field_info = Type.GetFields ();
+                               int nf = 0;
+                               for (int i = 0; i < field_info.Length; ++i) {
+                                       if (!field_info [i].IsStatic) {
+                                               if (field_info [i].Name == field) {
+                                                       fields [nf] = value;
+                                                       return;
+                                               }
+                                               nf++;
+                                       }
+                               }
+                               throw new ArgumentException ("Unknown struct field '" + field + "'.", "field");
+                       }
                }
 
                internal void SetField (int index, Value value) {
index ce4c285015ab48f8d2f0c0fdde2df7fb765ea3fa..cb2cafdb71401b7669d1ca28d17335594dd67f64 100644 (file)
@@ -227,10 +227,14 @@ namespace Mono.Debugger.Soft
                }
 
                public void EnableEvents (params EventType[] events) {
+                       EnableEvents (events, SuspendPolicy.All);
+               }
+
+               public void EnableEvents (EventType[] events, SuspendPolicy suspendPolicy) {
                        foreach (EventType etype in events) {
                                if (etype == EventType.Breakpoint)
                                        throw new ArgumentException ("Breakpoint events cannot be requested using EnableEvents", "events");
-                               conn.EnableEvent (etype, SuspendPolicy.All, null);
+                               conn.EnableEvent (etype, suspendPolicy, null);
                        }
                }
 
index dc4be1371e6eda1e3d9d794365fa95d1ff0671c9..e72069f0cab17d186e6e5fa9f8fe655e2a7d26ae 100644 (file)
@@ -361,6 +361,7 @@ public class Tests : TestsBase, ITest2
                ss_regress_654694 ();
                ss_step_through ();
                ss_recursive (1);
+               ss_fp_clobber ();
        }
 
        [MethodImplAttribute (MethodImplOptions.NoInlining)]
@@ -485,6 +486,21 @@ public class Tests : TestsBase, ITest2
                ss_recursive (n + 1);
        }
 
+       [MethodImplAttribute (MethodImplOptions.NoInlining)]
+       public static void ss_fp_clobber () {
+               double v = ss_fp_clobber_1 (5.0);
+               ss_fp_clobber_2 (v);
+       }
+
+       [MethodImplAttribute (MethodImplOptions.NoInlining)]
+       public static double ss_fp_clobber_1 (double d) {
+               return d + 2.0;
+       }
+
+       [MethodImplAttribute (MethodImplOptions.NoInlining)]
+       public static void ss_fp_clobber_2 (double d) {
+       }
+
        [MethodImplAttribute (MethodImplOptions.NoInlining)]
        public static bool is_even (int i) {
                return i % 2 == 0;
@@ -597,8 +613,9 @@ public class Tests : TestsBase, ITest2
        [MethodImplAttribute (MethodImplOptions.NoInlining)]
        public static void locals () {
                string s = null;
+               var astruct = new AStruct () { i = 42 };
                locals1 (null);
-               locals2<string> (null, 5, "ABC", ref s);
+               locals2<string> (null, 5, "ABC", ref s, ref astruct);
                locals3 ();
                locals6 ();
                locals7<int> (22);
@@ -624,7 +641,7 @@ public class Tests : TestsBase, ITest2
 #if NET_4_5
        [StateMachine (typeof (int))]
 #endif
-       public static void locals2<T> (string[] args, int arg, T t, ref string rs) {
+       public static void locals2<T> (string[] args, int arg, T t, ref string rs, ref AStruct astruct) {
                long i = 42;
                string s = "AB";
 
@@ -633,6 +650,7 @@ public class Tests : TestsBase, ITest2
                                i ++;
                        if (t != null)
                                i ++;
+                       astruct = new AStruct ();
                }
                rs = "A";
        }
index f66b1b13a5be0eaa9063b620f9a17775e507f1e4..ea2c2b9f3327e7cea6ea77e08aa924e9a287bc9b 100644 (file)
@@ -551,7 +551,20 @@ public class DebuggerTests
                var f = e.Thread.GetFrames () [0];
                assert_location (e, "ss_recursive");
                AssertValue (1, f.GetValue (f.Method.GetLocal ("n")));
+               req.Disable ();
 
+               // Check that single stepping doesn't clobber fp values
+               e = run_until ("ss_fp_clobber");
+               req = create_step (e);
+               while (true) {
+                       f = e.Thread.GetFrames ()[0];
+                       e = step_into ();
+                       if ((e as StepEvent).Method.Name == "ss_fp_clobber_2")
+                               break;
+                       e = step_into ();
+               }
+               f = e.Thread.GetFrames ()[0];
+               AssertValue (7.0, f.GetValue (f.Method.GetParameters ()[0]));
                req.Disable ();
        }
 
@@ -1467,8 +1480,8 @@ public class DebuggerTests
                StackFrame frame = e.Thread.GetFrames () [0];
 
                var locals = frame.Method.GetLocals ();
-               Assert.AreEqual (7, locals.Length);
-               for (int i = 0; i < 7; ++i) {
+               Assert.AreEqual (8, locals.Length);
+               for (int i = 0; i < 8; ++i) {
                        if (locals [i].Name == "args") {
                                Assert.IsTrue (locals [i].IsArg);
                                Assert.AreEqual ("String[]", locals [i].Type.Name);
@@ -1491,6 +1504,7 @@ public class DebuggerTests
                        } else if (locals [i].Name == "rs") {
                                Assert.IsTrue (locals [i].IsArg);
                                Assert.AreEqual ("String", locals [i].Type.Name);
+                       } else if (locals [i].Name == "astruct") {
                        } else {
                                Assert.Fail ();
                        }
@@ -2404,6 +2418,14 @@ public class DebuggerTests
                frame.SetValue (p, vm.RootDomain.CreateString ("DEF2"));
                AssertValue ("DEF2", frame.GetValue (p));
 
+               // byref struct
+               p = frame.Method.GetParameters ()[4];
+               var v = frame.GetValue (p) as StructMirror;
+               v ["i"] = vm.CreateValue (43);
+               frame.SetValue (p, v);
+               v = frame.GetValue (p) as StructMirror;
+               AssertValue (43, v ["i"]);
+
                // argument checking
 
                // variable null
diff --git a/mcs/class/Mono.Dynamic.Interpreter/Assembly/AssemblyInfo.cs b/mcs/class/Mono.Dynamic.Interpreter/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..9613d89
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// AssemblyInfo.cs
+//
+// Authors:
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Copyright (c) 2014 Xamarin Inc. (http://www.xamarin.com)
+//
+// 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.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the assembly
+
+[assembly: AssemblyTitle ("Mono.Dynamic.Interpreter.dll")]
+[assembly: AssemblyDescription ("Mono.Dynamic.Interpreter.dll")]
+[assembly: AssemblyDefaultAlias ("Mono.Dynamic.Interpreter.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: CLSCompliant (true)]
+
diff --git a/mcs/class/Mono.Dynamic.Interpreter/Makefile b/mcs/class/Mono.Dynamic.Interpreter/Makefile
new file mode 100644 (file)
index 0000000..bb8851a
--- /dev/null
@@ -0,0 +1,13 @@
+thisdir = class/Mono.Dynamic.Interpreter
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = Mono.Dynamic.Interpreter.dll
+
+LIB_MCS_FLAGS = -r:System.dll -r:System.Core.dll -r:System.Numerics.dll \
+       -d:FEATURE_CORE_DLR,FEATURE_NUMERICS,FEATURE_DBNULL,FEATURE_DEFAULT_PARAMETER_VALUE,FEATURE_GET_TYPE_INFO,FEATURE_VARIANCE,FEATURE_SERIALIZATION,CLR45 \
+       -d:MONO_INTERPRETER \
+       -delaysign -keyfile:../mono.pub
+
+include ../../build/library.make
+
diff --git a/mcs/class/Mono.Dynamic.Interpreter/Mono.Dynamic.Interpreter.dll.sources b/mcs/class/Mono.Dynamic.Interpreter/Mono.Dynamic.Interpreter.dll.sources
new file mode 100644 (file)
index 0000000..8744110
--- /dev/null
@@ -0,0 +1,99 @@
+../../build/common/Consts.cs
+Assembly/AssemblyInfo.cs
+
+../dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs
+../dlr/Runtime/Microsoft.Scripting/InvalidImplementationException.cs
+../dlr/Runtime/Microsoft.Scripting/PlatformAdaptationLayer.cs
+../dlr/Runtime/Microsoft.Scripting/Stubs.cs
+
+../dlr/Runtime/Microsoft.Scripting/Runtime/NotNullAttribute.cs
+../dlr/Runtime/Microsoft.Scripting/Runtime/ParamDictionaryAttribute.cs
+
+../dlr/Runtime/Microsoft.Dynamic/DebugOptions.cs
+../dlr/Runtime/Microsoft.Dynamic/MultiRuntimeAwareAttribute.cs
+../dlr/Runtime/Microsoft.Dynamic/PerfTrack.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Actions/Dummy.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Ast/BinaryExpression.cs
+../dlr/Runtime/Microsoft.Dynamic/Ast/ConstantExpression.cs
+../dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs
+../dlr/Runtime/Microsoft.Dynamic/Ast/LightLambdaExpression.cs
+../dlr/Runtime/Microsoft.Dynamic/Ast/UnaryExpression.cs
+../dlr/Runtime/Microsoft.Dynamic/Ast/Utils.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs
+../dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs
+../dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.cs
+../dlr/Runtime/Microsoft.Dynamic/Generation/DelegateHelpers.Generated.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/BranchLabel.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/ILightCallSiteBinder.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/InterpretedFrame.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Interpreter.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/LightCompiler.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/LightDelegateCreator.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/LocalVariables.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/LoopCompiler.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/RuntimeVariables.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AddInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/AndInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/CallInstruction.Generated.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ControlFlowInstructions.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DivInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructionN.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicInstructions.Generated.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/DynamicSplatInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/EqualInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/GreaterThanInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionFactory.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LabelInfo.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LessThanInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ModInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/MulInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NegateInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NotEqualInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/NumericConvertInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/StackOperations.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShlInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ShrInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/SubInstruction.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/TypeOperations.cs
+../dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Math/BigIntegerV4.cs
+../dlr/Runtime/Microsoft.Dynamic/Math/Complex64.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs
+../dlr/Runtime/Microsoft.Dynamic/Runtime/DynamicNull.cs
+../dlr/Runtime/Microsoft.Dynamic/Runtime/ExceptionHelpers.cs
+../dlr/Runtime/Microsoft.Dynamic/Runtime/ScriptingRuntimeHelpers.cs
+
+../dlr/Runtime/Microsoft.Dynamic/Utils/ArrayUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/Assert.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/CacheDict.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/ContractUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/CollectionExtensions.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/CollectionUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/DynamicUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/ExceptionFactory.Generated.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/HybridReferenceDictionary.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/ListEqualityComparer.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/MathUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/ReflectionUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/StringUtils.cs
+../dlr/Runtime/Microsoft.Dynamic/Utils/TypeUtils.cs
index 7488f79b56f2217deecc2832d1f13822ee9bfc40..7ba53e922bf7d1dd53db2206246a8281c522af7c 100644 (file)
@@ -2305,7 +2305,7 @@ namespace Mono.Unix.Native {
                        // Syscall to getpwnam to retrieve user uid
                        Passwd pw = Syscall.getpwnam (username);
                        if (pw == null)
-                               throw new ArgumentException (string.Format ("User {0} does not exists",username), "username");
+                               throw new ArgumentException (string.Format ("User {0} does not exist", username), "username");
                        return getgrouplist (pw);
                }
 
index 824eaf70ab4ecc773d6998f9b8f0094f56d6ae28..7135c45e3c73202b0b0188ba0ffd22e5077d71b7 100644 (file)
@@ -2,6 +2,9 @@ thisdir = class/Mono.XBuild.Tasks
 SUBDIRS = 
 include ../../build/rules.make
 
+XBUILD_DIR=$(topdir)/tools/xbuild
+include $(XBUILD_DIR)/xbuild.make
+
 LIBRARY = Mono.XBuild.Tasks.dll
 
 LIB_MCS_FLAGS = \
@@ -9,8 +12,6 @@ LIB_MCS_FLAGS = \
        /r:System.dll                           \
        /r:System.Xml.dll
 
-export TESTING_MONO=a
-XBUILD_DIR=../../tools/xbuild
-include $(XBUILD_DIR)/xbuild_targets.make
+include $(XBUILD_DIR)/xbuild_test.make
 
 include ../../build/library.make
diff --git a/mcs/class/Moonlight.Build.Tasks/ChangeLog b/mcs/class/Moonlight.Build.Tasks/ChangeLog
deleted file mode 100644 (file)
index 7e63080..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-2010-04-13  Ankit Jain  <jankit@novell.com>
-
-       * Initial commit.
diff --git a/mcs/class/Moonlight.Build.Tasks/Makefile b/mcs/class/Moonlight.Build.Tasks/Makefile
deleted file mode 100644 (file)
index 5452bf8..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-thisdir = class/Moonlight.Build.Tasks
-SUBDIRS = 
-include ../../build/rules.make
-
-LIBRARY = Moonlight.Build.Tasks.dll
-LIBRARY_NAME = Moonlight.Build.Tasks.dll
-
-ifeq (3.5, $(FRAMEWORK_VERSION))
-NAME_SUFFIX = .v3.5
-else
-ifeq (4, $(FRAMEWORK_VERSION_MAJOR))
-NAME_SUFFIX = .v4.0
-endif
-endif
-
-NO_INSTALL = yes
-NO_TEST = yes
-NO_SIGN_ASSEMBLY = yes
-
-REFERENCES = \
-       /r:$(corlib)                            \
-       /r:System.dll                           \
-       /r:System.Xml.dll                       \
-       /r:Microsoft.Build.Engine.dll   \
-       /r:Microsoft.Build.Framework.dll        \
-       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll \
-       /r:Microsoft.Build.Tasks$(NAME_SUFFIX).dll \
-       /r:ICSharpCode.SharpZipLib.dll
-
-LIB_MCS_FLAGS = \
-       $(REFERENCES) \
-       $(RESOURCE_FILES:%=-resource:%)
-
-RESOURCE_FILES = Moonlight.Build.Tasks/PreviewTemplate.html
-
-EXTRA_DISTFILES = $(RESOURCE_FILES)
-
-XBUILD_DIR=../../tools/xbuild
-include $(XBUILD_DIR)/xbuild_targets.make
-
-include ../../build/library.make
-
-SILVERLIGHT_DIR = $(DESTDIR)$(mono_libdir)/mono/xbuild/Microsoft/Silverlight
-
-install-local: install-lib
-
-install-lib: $(the_lib)
-       -$(MKINSTALLDIRS) $(SILVERLIGHT_DIR)/v2.0
-       -$(MKINSTALLDIRS) $(SILVERLIGHT_DIR)/v3.0
-       $(INSTALL_DATA) $(topdir)/class/lib/$(PROFILE)/$(LIBRARY_NAME) $(SILVERLIGHT_DIR)/v2.0
-       $(INSTALL_DATA) $(topdir)/class/lib/$(PROFILE)/$(LIBRARY_NAME) $(SILVERLIGHT_DIR)/v3.0
-
-uninstall-local: uninstall-lib
-
-uninstall-lib:
-       -rm -f $(SILVERLIGHT_DIR)/v2.0/$(LIBRARY_NAME)
-       -rm -f $(SILVERLIGHT_DIR)/v3.0/$(LIBRARY_NAME)
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_2_0.csproj b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_2_0.csproj
deleted file mode 100644 (file)
index 2c39089..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>\r
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
-  <PropertyGroup>\r
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
-    <SchemaVersion>2.0</SchemaVersion>\r
-    <ProjectGuid>{A397D71E-CB6B-4442-91BC-4F1C801584C1}</ProjectGuid>\r
-    <OutputType>Library</OutputType>\r
-    <NoWarn>1699</NoWarn>\r
-    <OutputPath>bin\Debug\Moonlight.Build.Tasks-net_2_0</OutputPath>\r
-    <NoStdLib>True</NoStdLib>\r
-    <NoConfig>True</NoConfig>\r
-    \r
-    <AppDesignerFolder>Properties</AppDesignerFolder>\r
-    <RootNamespace>\r
-    </RootNamespace>\r
-    <AssemblyName>Moonlight.Build.Tasks</AssemblyName>\r
-    <TargetFrameworkVersion>v2.0</TargetFrameworkVersion>\r
-    <FileAlignment>512</FileAlignment>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
-    <DebugSymbols>true</DebugSymbols>\r
-    <DebugType>full</DebugType>\r
-    <NoWarn>1699</NoWarn>\r
-    <Optimize>false</Optimize>\r
-    <DefineConstants>DEBUG;TRACE;NET_1_1;NET_2_0</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
-    <DebugType>pdbonly</DebugType>\r
-    <NoWarn>1699</NoWarn>\r
-    <Optimize>true</Optimize>\r
-    <DefineConstants>NET_1_1;NET_2_0</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <!-- Set AddAdditionalExplicitAssemblyReferences to false, otherwise if targetting .NET4.0, \r
-  Microsoft.NETFramework.props will force a dependency on the assembly System.Core. This\r
-  is a problem to compile the Mono mscorlib.dll -->\r
-  <PropertyGroup>\r
-    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>\r
-  </PropertyGroup>\r
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
-  <ItemGroup>\r
-    <Compile Include="Moonlight.Build.Tasks\CreateTestPage.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GenerateMoonlightManifest.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GenerateXap.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GetMoonlightFrameworkPath.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\Respack.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\XamlG.cs" />\r  </ItemGroup>\r
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
-       Other similar extension points exist, see Microsoft.Common.targets.\r
-  <Target Name="BeforeBuild">\r
-  </Target>\r
-  <Target Name="AfterBuild">\r
-  </Target>\r
-  -->\r
-  <PropertyGroup>\r
-    <PreBuildEvent>\r
-\r
-    </PreBuildEvent>\r
-    <PostBuildEvent>\r
-      xcopy $(TargetName).* $(ProjectDir)..\lib\net_2_0\ /Y /R /D\r
-  </PostBuildEvent>\r
-  </PropertyGroup>\r
-  <ItemGroup>\r
-    <ProjectReference Include="..\corlib\corlib-net_2_0.csproj">\r
-      <Project>{EB7444A6-C3E6-4224-BDB0-63CA3B4F2B87}</Project>\r
-      <Name>corlib\corlib-net_2_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\System\System-net_2_0-2.csproj">\r
-      <Project>{79F25FD7-0D76-4526-AF39-1A648649A827}</Project>\r
-      <Name>System\System-net_2_0-2</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\System.XML\System.Xml-net_2_0-1.csproj">\r
-      <Project>{D9776E38-7673-45F6-BF19-7B77830DF9CA}</Project>\r
-      <Name>System.XML\System.Xml-net_2_0-1</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Engine\Microsoft.Build.Engine-net_2_0.csproj">\r
-      <Project>{E8E948B8-6DCF-48F2-A6BC-04309AED8740}</Project>\r
-      <Name>Microsoft.Build.Engine\Microsoft.Build.Engine-net_2_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Framework\Microsoft.Build.Framework-net_2_0.csproj">\r
-      <Project>{AB5EDD8C-84A4-4F96-80EE-1B6F3A86785B}</Project>\r
-      <Name>Microsoft.Build.Framework\Microsoft.Build.Framework-net_2_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Utilities\Microsoft.Build.Utilities-net_2_0.csproj">\r
-      <Project>{4AC4EDEE-4895-4CF9-84DF-9419E6980F38}</Project>\r
-      <Name>Microsoft.Build.Utilities\Microsoft.Build.Utilities-net_2_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Tasks\Microsoft.Build.Tasks-net_2_0.csproj">\r
-      <Project>{3DD52713-DB38-4D0D-8692-650B8821B047}</Project>\r
-      <Name>Microsoft.Build.Tasks\Microsoft.Build.Tasks-net_2_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\ICSharpCode.SharpZipLib\ICSharpCode.SharpZipLib-net_2_0.csproj">\r
-      <Project>{065A843F-C16B-4F2E-9560-69440147EDB2}</Project>\r
-      <Name>ICSharpCode.SharpZipLib\ICSharpCode.SharpZipLib-net_2_0</Name>\r
-    </ProjectReference>\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <Folder Include="Properties\" />\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <EmbeddedResource Include="Moonlight.Build.Tasks/PreviewTemplate.html">\r
-      <LogicalName>PreviewTemplate.html</LogicalName>\r
-    </EmbeddedResource>\r
-  </ItemGroup>\r
-</Project>
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_4_0.csproj b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_4_0.csproj
deleted file mode 100644 (file)
index 7469cf3..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>\r
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
-  <PropertyGroup>\r
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
-    <SchemaVersion>2.0</SchemaVersion>\r
-    <ProjectGuid>{8B495C4E-D5D2-4642-9481-F761DDD47ABD}</ProjectGuid>\r
-    <OutputType>Library</OutputType>\r
-    <NoWarn>1699</NoWarn>\r
-    <OutputPath>bin\Debug\Moonlight.Build.Tasks-net_4_0</OutputPath>\r
-    <NoStdLib>True</NoStdLib>\r
-    <NoConfig>True</NoConfig>\r
-    \r
-    <AppDesignerFolder>Properties</AppDesignerFolder>\r
-    <RootNamespace>\r
-    </RootNamespace>\r
-    <AssemblyName>Moonlight.Build.Tasks</AssemblyName>\r
-    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>\r
-    <FileAlignment>512</FileAlignment>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
-    <DebugSymbols>true</DebugSymbols>\r
-    <DebugType>full</DebugType>\r
-    <NoWarn>1699</NoWarn>\r
-    <Optimize>false</Optimize>\r
-    <DefineConstants>DEBUG;TRACE;NET_1_1;NET_2_0;NET_3_0;NET_3_5;NET_4_0</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
-    <DebugType>pdbonly</DebugType>\r
-    <NoWarn>1699</NoWarn>\r
-    <Optimize>true</Optimize>\r
-    <DefineConstants>NET_1_1;NET_2_0;NET_3_0;NET_3_5;NET_4_0</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <!-- Set AddAdditionalExplicitAssemblyReferences to false, otherwise if targetting .NET4.0, \r
-  Microsoft.NETFramework.props will force a dependency on the assembly System.Core. This\r
-  is a problem to compile the Mono mscorlib.dll -->\r
-  <PropertyGroup>\r
-    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>\r
-  </PropertyGroup>\r
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
-  <ItemGroup>\r
-    <Compile Include="Moonlight.Build.Tasks\CreateTestPage.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GenerateMoonlightManifest.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GenerateXap.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GetMoonlightFrameworkPath.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\Respack.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\XamlG.cs" />\r  </ItemGroup>\r
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
-       Other similar extension points exist, see Microsoft.Common.targets.\r
-  <Target Name="BeforeBuild">\r
-  </Target>\r
-  <Target Name="AfterBuild">\r
-  </Target>\r
-  -->\r
-  <PropertyGroup>\r
-    <PreBuildEvent>\r
-\r
-    </PreBuildEvent>\r
-    <PostBuildEvent>\r
-      xcopy $(TargetName).* $(ProjectDir)..\lib\net_4_0\ /Y /R /D\r
-  </PostBuildEvent>\r
-  </PropertyGroup>\r
-  <ItemGroup>\r
-    <ProjectReference Include="..\corlib\corlib-net_4_0.csproj">\r
-      <Project>{3874F10B-9AE4-4A7E-873B-42FFDCE80CB7}</Project>\r
-      <Name>corlib\corlib-net_4_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\System\System-net_4_0-2.csproj">\r
-      <Project>{8260E24F-1471-4320-AB5B-7CC7B68521E3}</Project>\r
-      <Name>System\System-net_4_0-2</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\System.XML\System.Xml-net_4_0-1.csproj">\r
-      <Project>{51720A26-B4D9-4B84-8CB5-9CBA57477FBB}</Project>\r
-      <Name>System.XML\System.Xml-net_4_0-1</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Engine\Microsoft.Build.Engine-net_4_0.csproj">\r
-      <Project>{9B0AC297-CB85-43C1-8C18-12997CF1B78D}</Project>\r
-      <Name>Microsoft.Build.Engine\Microsoft.Build.Engine-net_4_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Framework\Microsoft.Build.Framework-net_4_0.csproj">\r
-      <Project>{1D4BCF4D-31D1-4F92-A2B2-D9E41A640649}</Project>\r
-      <Name>Microsoft.Build.Framework\Microsoft.Build.Framework-net_4_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Utilities\Microsoft.Build.Utilities-net_4_0.csproj">\r
-      <Project>{A20F004B-16AC-44DE-A14E-2C2B5E9F72BE}</Project>\r
-      <Name>Microsoft.Build.Utilities\Microsoft.Build.Utilities-net_4_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Tasks\Microsoft.Build.Tasks-net_4_0.csproj">\r
-      <Project>{0F2C25D7-DF2E-4F4B-85D8-7EFC4DCD3B0C}</Project>\r
-      <Name>Microsoft.Build.Tasks\Microsoft.Build.Tasks-net_4_0</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\ICSharpCode.SharpZipLib\ICSharpCode.SharpZipLib-net_4_0.csproj">\r
-      <Project>{2DE2CFB0-3166-41D9-B0B5-EFBE309DD7B7}</Project>\r
-      <Name>ICSharpCode.SharpZipLib\ICSharpCode.SharpZipLib-net_4_0</Name>\r
-    </ProjectReference>\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <Folder Include="Properties\" />\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <EmbeddedResource Include="Moonlight.Build.Tasks/PreviewTemplate.html">\r
-      <LogicalName>PreviewTemplate.html</LogicalName>\r
-    </EmbeddedResource>\r
-  </ItemGroup>\r
-</Project>
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_4_5.csproj b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks-net_4_5.csproj
deleted file mode 100644 (file)
index 66141f0..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>\r
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
-  <PropertyGroup>\r
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
-    <SchemaVersion>2.0</SchemaVersion>\r
-    <ProjectGuid>{C1BA77F3-938B-4598-BD75-5E9578827F47}</ProjectGuid>\r
-    <OutputType>Library</OutputType>\r
-    <NoWarn>1699</NoWarn>\r
-    <OutputPath>bin\Debug\Moonlight.Build.Tasks-net_4_5</OutputPath>\r
-    <NoStdLib>True</NoStdLib>\r
-    <NoConfig>True</NoConfig>\r
-    \r
-    <AppDesignerFolder>Properties</AppDesignerFolder>\r
-    <RootNamespace>\r
-    </RootNamespace>\r
-    <AssemblyName>Moonlight.Build.Tasks</AssemblyName>\r
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r
-    <FileAlignment>512</FileAlignment>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
-    <DebugSymbols>true</DebugSymbols>\r
-    <DebugType>full</DebugType>\r
-    <NoWarn>1699</NoWarn>\r
-    <Optimize>false</Optimize>\r
-    <DefineConstants>DEBUG;TRACE;NET_1_1;NET_2_0;NET_3_0;NET_3_5;NET_4_0;NET_4_5</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
-    <DebugType>pdbonly</DebugType>\r
-    <NoWarn>1699</NoWarn>\r
-    <Optimize>true</Optimize>\r
-    <DefineConstants>NET_1_1;NET_2_0;NET_3_0;NET_3_5;NET_4_0;NET_4_5</DefineConstants>\r
-    <ErrorReport>prompt</ErrorReport>\r
-    <WarningLevel>4</WarningLevel>\r
-  </PropertyGroup>\r
-  <!-- Set AddAdditionalExplicitAssemblyReferences to false, otherwise if targetting .NET4.0, \r
-  Microsoft.NETFramework.props will force a dependency on the assembly System.Core. This\r
-  is a problem to compile the Mono mscorlib.dll -->\r
-  <PropertyGroup>\r
-    <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>\r
-  </PropertyGroup>\r
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
-  <ItemGroup>\r
-    <Compile Include="Moonlight.Build.Tasks\CreateTestPage.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GenerateMoonlightManifest.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GenerateXap.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\GetMoonlightFrameworkPath.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\Respack.cs" />\r
-    <Compile Include="Moonlight.Build.Tasks\XamlG.cs" />\r  </ItemGroup>\r
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
-       Other similar extension points exist, see Microsoft.Common.targets.\r
-  <Target Name="BeforeBuild">\r
-  </Target>\r
-  <Target Name="AfterBuild">\r
-  </Target>\r
-  -->\r
-  <PropertyGroup>\r
-    <PreBuildEvent>\r
-\r
-    </PreBuildEvent>\r
-    <PostBuildEvent>\r
-      xcopy $(TargetName).* $(ProjectDir)..\lib\net_4_5\ /Y /R /D\r
-  </PostBuildEvent>\r
-  </PropertyGroup>\r
-  <ItemGroup>\r
-    <ProjectReference Include="..\corlib\corlib-net_4_5.csproj">\r
-      <Project>{07C1F58B-9E99-47F8-A847-79EDA5157DA8}</Project>\r
-      <Name>corlib\corlib-net_4_5</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\System\System-net_4_5-2.csproj">\r
-      <Project>{38FCD731-0E11-46F7-A31B-DCBE853AD8D7}</Project>\r
-      <Name>System\System-net_4_5-2</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\System.XML\System.Xml-net_4_5-1.csproj">\r
-      <Project>{4ED6CCE8-8E8A-4D82-8BCA-3EA4D4203AA4}</Project>\r
-      <Name>System.XML\System.Xml-net_4_5-1</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Engine\Microsoft.Build.Engine-net_4_5.csproj">\r
-      <Project>{0DA63190-E6E1-41C5-B683-A54FADBE61CB}</Project>\r
-      <Name>Microsoft.Build.Engine\Microsoft.Build.Engine-net_4_5</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Framework\Microsoft.Build.Framework-net_4_5.csproj">\r
-      <Project>{2BAFB878-D329-46A5-93AF-5A4ECD403A13}</Project>\r
-      <Name>Microsoft.Build.Framework\Microsoft.Build.Framework-net_4_5</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Utilities\Microsoft.Build.Utilities-net_4_5.csproj">\r
-      <Project>{5CD66EA1-51EB-48EE-8C1C-DDFD23E22C38}</Project>\r
-      <Name>Microsoft.Build.Utilities\Microsoft.Build.Utilities-net_4_5</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\Microsoft.Build.Tasks\Microsoft.Build.Tasks-net_4_5.csproj">\r
-      <Project>{B0995E00-BF37-4B8A-8229-285C060E5957}</Project>\r
-      <Name>Microsoft.Build.Tasks\Microsoft.Build.Tasks-net_4_5</Name>\r
-    </ProjectReference>\r
-    <ProjectReference Include="..\ICSharpCode.SharpZipLib\ICSharpCode.SharpZipLib-net_4_5.csproj">\r
-      <Project>{039AD56A-E91B-4803-8328-287F70B61D14}</Project>\r
-      <Name>ICSharpCode.SharpZipLib\ICSharpCode.SharpZipLib-net_4_5</Name>\r
-    </ProjectReference>\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <Folder Include="Properties\" />\r
-  </ItemGroup>\r
-  <ItemGroup>\r
-    <EmbeddedResource Include="Moonlight.Build.Tasks/PreviewTemplate.html">\r
-      <LogicalName>PreviewTemplate.html</LogicalName>\r
-    </EmbeddedResource>\r
-  </ItemGroup>\r
-</Project>
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks.dll.sources b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks.dll.sources
deleted file mode 100644 (file)
index 74c3a27..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-Moonlight.Build.Tasks/GenerateXap.cs
-Moonlight.Build.Tasks/XamlG.cs
-Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs
-Moonlight.Build.Tasks/GenerateMoonlightManifest.cs
-Moonlight.Build.Tasks/CreateTestPage.cs
-Moonlight.Build.Tasks/Respack.cs
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/ChangeLog b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/ChangeLog
deleted file mode 100644 (file)
index f622072..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-2010-07-16  Ankit Jain  <jankit@novell.com>
-
-       * XamlG.cs (Execute): Fix earlier commit, include the filename.
-
-2010-07-16  Ankit Jain  <jankit@novell.com>
-
-       * Respack.cs (Execute): Skip if output file is up-to-date wrt
-       the input files. Bug reported by Rolf.
-
-2010-07-16  Ankit Jain  <jankit@novell.com>
-
-       * XamlG.cs: Fix arg to XamlGCompiler, to use path relative to project
-       dir. Bug uncovered by Rolf.
-
-2010-04-13  Ankit Jain  <jankit@novell.com>
-
-       * CreateTestPage.cs:
-       * GenerateMoonlightManifest.cs:
-       * GetMoonlightFrameworkPath.cs:
-       * GenerateXap.cs:
-       * Respack.cs:
-       * XamlG.cs:
-       MSBuild tasks for building silverlight projects.
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/CreateTestPage.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/CreateTestPage.cs
deleted file mode 100644 (file)
index 2805169..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-//
-// CreateTestPage.cs: Generates test page for moonlight app
-//
-// Author:
-//     Michael Hutchinson <mhutchinson@novell.com>
-//     Ankit Jain <jankit@novell.com>
-//
-// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
-// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
-//
-// 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.IO;
-using System.Reflection;
-using System.Text;
-
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-
-namespace Moonlight.Build.Tasks {
-       public class CreateTestPage : Task {
-
-               public override bool Execute ()
-               {
-                       Log.LogMessage (MessageImportance.Low, "Generating test page {0}", XapFilename);
-
-                       var sb = new StringBuilder ();
-                       using (var sr = new StreamReader (Assembly.GetExecutingAssembly ().GetManifestResourceStream ("PreviewTemplate.html")))
-                               sb.Append (sr.ReadToEnd ());
-
-                       sb.Replace ("@TITLE@", Title);
-                       sb.Replace ("@XAP_FILE@", XapFilename);
-
-                       try{
-                               File.WriteAllText (TestPageFilename, sb.ToString ());
-                       } catch (IOException e) {
-                               Log.LogError (String.Format (
-                                               "Error generating test page file {0}: {1}", TestPageFilename, e.Message));
-                               return false;
-                       }
-
-                       return true;
-               }
-
-               [Required]
-               public string XapFilename {
-                       get; set;
-               }
-
-               [Required]
-               public string Title {
-                       get; set;
-               }
-
-               [Required]
-               [Output]
-               public string TestPageFilename {
-                       get; set;
-               }
-       }
-}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateMoonlightManifest.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateMoonlightManifest.cs
deleted file mode 100644 (file)
index 4b7e7a3..0000000
+++ /dev/null
@@ -1,179 +0,0 @@
-//
-// GenerateMoonlightManifest.cs
-//
-// Author:
-//     Michael Hutchinson <mhutchinson@novell.com>
-//     Ankit Jain <jankit@novell.com>
-//
-// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
-// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
-//
-// 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;
-using System.Collections.Generic;
-using System.IO;
-using System.CodeDom;
-using System.CodeDom.Compiler;
-using System.Xml;
-
-using Microsoft.CSharp;
-
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-
-namespace Moonlight.Build.Tasks {
-       public class GenerateMoonlightManifest : Task {
-
-               public override bool Execute ()
-               {
-                       return GenerateManifest ();
-               }
-
-               bool GenerateManifest ()
-               {
-                       const string depNS = "http://schemas.microsoft.com/client/2007/deployment";
-
-                       string template = null;
-                       var manifest = ManifestFile.ItemSpec;
-                       Log.LogMessage (MessageImportance.Normal, "Generating manifest file {0}", manifest);
-
-                       if (SilverlightManifestTemplate != null)
-                               template = String.IsNullOrEmpty (SilverlightManifestTemplate.ItemSpec) ?
-                                                       null :
-                                                       SilverlightManifestTemplate.GetMetadata ("FullPath");
-
-                       XmlDocument doc = new XmlDocument ();
-                       if (template != null) {
-                               if (!File.Exists (template)) {
-                                       Log.LogError ("Could not find manifest template '" +  template + "'.");
-                                       return false;
-                               }
-
-                               try {
-                                       doc.Load (template);
-                               } catch (XmlException ex) {
-                                       Log.LogError (null, null, null, template, ex.LineNumber, ex.LinePosition, 0, 0,
-                                                       "Error loading manifest template '" + ex.Source);
-                                       return false;
-                               } catch (Exception ex) {
-                                       Log.LogError ("Could not load manifest template '" +  template + "'.");
-                                       Log.LogMessage (MessageImportance.Low, "Could not load manifest template '" +  template + "': " + ex.ToString ());
-                                       return false;
-                               }
-
-                       } else {
-                               doc.LoadXml (@"<Deployment xmlns=""http://schemas.microsoft.com/client/2007/deployment"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""></Deployment>");
-                       }
-
-                       try {
-                               XmlNode deploymentNode = doc.DocumentElement;
-                               if (deploymentNode == null || deploymentNode.Name != "Deployment" || deploymentNode.NamespaceURI != depNS) {
-                                       Log.LogError ("Missing or invalid root <Deployment> element in manifest template '" +  template + "'.");
-                                       return false;
-                               }
-                               if (deploymentNode.Attributes["EntryPointAssembly"] == null)
-                                       deploymentNode.Attributes.Append (doc.CreateAttribute ("EntryPointAssembly")).Value =
-                                               EntryPointAssembly.GetMetadata ("Filename");
-
-                               if (!String.IsNullOrEmpty (SilverlightAppEntry) && deploymentNode.Attributes["EntryPointType"] == null)
-                                       deploymentNode.Attributes.Append (doc.CreateAttribute ("EntryPointType")).Value = SilverlightAppEntry;
-
-                               if (deploymentNode.Attributes["RuntimeVersion"] == null) {
-                                       //FIXME:
-                                       /*string fxVersion = MoonlightFrameworkBackend.GetFxVersion (proj.TargetFramework);
-
-                                       if (proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime) {
-                                               var package = proj.TargetRuntime.RuntimeAssemblyContext.GetPackage ("moonlight-web-" + fxVersion);
-                                               if (package != null && package.IsFrameworkPackage) {
-                                                       runtimeVersion = package.Version;
-                                               } else {
-                                                       LoggingService.LogWarning ("Moonlight core framework package not found, cannot determine " +
-                                                               "runtime version string. Falling back to default value.");
-                                               }
-                                       }*/
-
-                                       deploymentNode.Attributes.Append (doc.CreateAttribute ("RuntimeVersion")).Value =
-                                                       String.IsNullOrEmpty (RuntimeVersion) ? "2.0.31005.0" : RuntimeVersion;
-                               }
-
-                               XmlNamespaceManager mgr = new XmlNamespaceManager (doc.NameTable);
-                               mgr.AddNamespace ("dep", depNS);
-                               XmlNode partsNode = deploymentNode.SelectSingleNode ("dep:Deployment.Parts", mgr);
-                               if (partsNode == null)
-                                       partsNode = deploymentNode.AppendChild (doc.CreateElement ("Deployment.Parts", depNS));
-
-                               AddAssemblyPart (doc, partsNode, EntryPointAssembly);
-
-                               foreach (ITaskItem ref_item in References)
-                                       AddAssemblyPart (doc, partsNode, ref_item);
-                       } catch (XmlException ex) {
-                               Log.LogError (null, null, null, template, ex.LineNumber, ex.LinePosition, 0, 0,
-                                               "Error processing manifest template: '" + ex.Source);
-                               return false;
-                       }
-
-                       doc.Save (manifest);
-
-                       return true;
-               }
-
-               static void AddAssemblyPart (XmlDocument doc, XmlNode partsNode, ITaskItem filename)
-               {
-                       XmlNode child = doc.CreateElement ("AssemblyPart", "http://schemas.microsoft.com/client/2007/deployment");
-                       child.Attributes.Append (doc.CreateAttribute (
-                                               "Name", "http://schemas.microsoft.com/winfx/2006/xaml")).Value = filename.GetMetadata ("Filename");
-                       string subdir = filename.GetMetadata ("DestinationSubdirectory");
-                       child.Attributes.Append (doc.CreateAttribute ("Source")).Value = Path.Combine (subdir ?? String.Empty, Path.GetFileName (filename.ItemSpec));
-                       partsNode.AppendChild (child);
-               }
-
-               [Required]
-               [Output]
-               public ITaskItem ManifestFile {
-                       get; set;
-               }
-
-               [Required]
-               // with extension
-               public ITaskItem EntryPointAssembly {
-                       get; set;
-               }
-
-               [Required]
-               public ITaskItem[] References {
-                       get; set;
-               }
-
-               public ITaskItem SilverlightManifestTemplate {
-                       get; set;
-               }
-
-               public string SilverlightAppEntry {
-                       get; set;
-               }
-
-               public string RuntimeVersion {
-                       get; set;
-               }
-       }
-
-}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateXap.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateXap.cs
deleted file mode 100644 (file)
index 92082ac..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-//
-// GenerateXap.cs
-//
-// Author:
-//     Michael Hutchinson <mhutchinson@novell.com>
-//     Ankit Jain <jankit@novell.com>
-//
-// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
-// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
-//
-// 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;
-using System.Collections.Generic;
-using System.IO;
-using System.CodeDom;
-using System.CodeDom.Compiler;
-using System.Xml;
-
-using Microsoft.CSharp;
-
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-
-namespace Moonlight.Build.Tasks {
-       public class GenerateXap : Task {
-
-               public override bool Execute ()
-               {
-                       if (InputFiles.Length == 0)
-                               return true;
-
-                       return Zip ();
-               }
-
-               bool Zip ()
-               {
-                       var xapName = XapFilename.ItemSpec;
-                       if (File.Exists (xapName)) {
-                               DateTime lastMod = File.GetLastWriteTime (xapName);
-                               bool needsWrite = false;
-                               foreach (ITaskItem file_item in InputFiles) {
-                                       if (File.GetLastWriteTime (file_item.ItemSpec) > lastMod) {
-                                               needsWrite = true;
-                                               break;
-                                       }
-                               }
-                               if (!needsWrite) {
-                                       Log.LogMessage (MessageImportance.Low, "Skipping xap file {0} generation, its up-to date");
-                                       return true;
-                               }
-                       }
-
-                       Log.LogMessage (MessageImportance.Normal, "Generating compressed xap file {0}", xapName);
-                       try {
-                               using (FileStream fs = new FileStream (xapName, FileMode.Create)) {
-                                       var zip_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs);
-                                       zip_stream.SetLevel (9);
-
-                                       AddFilesToZip (InputFiles, zip_stream);
-                                       AddFilesToZip (LocalCopyReferences, zip_stream);
-
-                                       zip_stream.Finish ();
-                                       zip_stream.Close ();
-                               }
-                       } catch (IOException ex) {
-                               Log.LogError ("Error writing xap file.", ex);
-                               Log.LogMessage (MessageImportance.Low, "Error writing xap file:" + ex.ToString ());
-
-                               try {
-                                       if (File.Exists (xapName))
-                                               File.Delete (xapName);
-                               } catch {}
-
-                               return false;
-                       }
-
-                       return true;
-               }
-
-               void AddFilesToZip (ITaskItem [] files, ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream)
-               {
-                       if (files == null)
-                               return;
-
-                       foreach (ITaskItem item in files) {
-                               string target_path = item.GetMetadata ("TargetPath");
-                               if (String.IsNullOrEmpty (target_path))
-                                       target_path = Path.GetFileName (item.ItemSpec);
-
-                               zipStream.PutNextEntry (new ICSharpCode.SharpZipLib.Zip.ZipEntry (target_path));
-                               using (FileStream inStream = File.OpenRead (item.ItemSpec)) {
-                                       int readCount;
-                                       byte[] buffer = new byte[4096];
-
-                                       do {
-                                               readCount = inStream.Read (buffer, 0, buffer.Length);
-                                               zipStream.Write (buffer, 0, readCount);
-                                       } while (readCount > 0);
-                               }
-                       }
-               }
-
-               [Output]
-               [Required]
-               public ITaskItem XapFilename {
-                       get; set;
-               }
-
-               [Required]
-               public ITaskItem[] InputFiles {
-                       get; set;
-               }
-
-               public ITaskItem[] LocalCopyReferences {
-                       get; set;
-               }
-
-       }
-
-
-}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs
deleted file mode 100644 (file)
index 91de544..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-//
-// GetMoonlightFrameworkPath.cs
-//
-// Author:
-//     Michael Hutchinson <mhutchinson@novell.com>
-//     Ankit Jain <jankit@novell.com>
-//
-// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
-// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
-//
-// 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 SI = System.IO;
-
-using System;
-using System.Text;
-
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-
-namespace Moonlight.Build.Tasks {
-       public class GetMoonlightFrameworkPath : Task {
-
-               public override bool Execute ()
-               {
-                       return true;
-               }
-
-               [Required]
-               public string SilverlightVersion {
-                       get; set;
-               }
-
-               [Output]
-               public string FrameworkPath {
-                       get {
-                               if (string.IsNullOrEmpty (SilverlightVersion))
-                                       return FrameworkVersion30Path;
-
-                               return SI.Path.GetFullPath (
-                                               PathCombine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20),
-                                               "..", "..", "moonlight", SilverlightVersion));
-                       }
-               }
-
-               [Output]
-               public string FrameworkVersion20Path {
-                       get {
-                               return SI.Path.GetFullPath (
-                                               PathCombine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20),
-                                               "..", "..", "moonlight", "2.0"));
-                       }
-               }
-
-               [Output]
-               public string FrameworkVersion30Path {
-                       get {
-                               return SI.Path.GetFullPath (
-                                               PathCombine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20),
-                                               "..", "..", "moonlight", "3.0"));
-                       }
-               }
-
-               static string PathCombine (string path1, params string[] parts)
-               {
-                       StringBuilder sb = new StringBuilder ();
-                       sb.Append (path1);
-                       foreach (string part in parts)
-                               sb.AppendFormat ("{0}{1}", SI.Path.DirectorySeparatorChar, part);
-
-                       return sb.ToString ();
-               }
-       }
-}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/PreviewTemplate.html b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/PreviewTemplate.html
deleted file mode 100644 (file)
index 2be0575..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" >
-<head>
-    <title>@TITLE@</title>
-
-    <style type="text/css">
-    html, body {
-           height: 100%;
-           overflow: auto;
-    }
-    body {
-           padding: 0;
-           margin: 0;
-    }
-    #silverlightControlHost {
-           height: 100%;
-    }
-    </style>
-    
-    <script type="text/javascript">
-        function onSilverlightError(sender, args) {
-        
-            var appSource = "";
-            if (sender != null && sender != 0) {
-                appSource = sender.getHost().Source;
-            } 
-            var errorType = args.ErrorType;
-            var iErrorCode = args.ErrorCode;
-            
-            var errMsg = "Unhandled Error in Silverlight 2 Application " +  appSource + "\n" ;
-
-            errMsg += "Code: "+ iErrorCode + "    \n";
-            errMsg += "Category: " + errorType + "       \n";
-            errMsg += "Message: " + args.ErrorMessage + "     \n";
-
-            if (errorType == "ParserError")
-            {
-                errMsg += "File: " + args.xamlFile + "     \n";
-                errMsg += "Line: " + args.lineNumber + "     \n";
-                errMsg += "Position: " + args.charPosition + "     \n";
-            }
-            else if (errorType == "RuntimeError")
-            {           
-                if (args.lineNumber != 0)
-                {
-                    errMsg += "Line: " + args.lineNumber + "     \n";
-                    errMsg += "Position: " +  args.charPosition + "     \n";
-                }
-                errMsg += "MethodName: " + args.methodName + "     \n";
-            }
-
-            throw new Error(errMsg);
-        }
-    </script>
-</head>
-
-<body>
-    <!-- Runtime errors from Silverlight will be displayed here.
-       This will contain debugging information and should be removed or hidden when debugging is completed -->
-       <div id='errorLocation' style="font-size: small;color: Gray;"></div>
-
-    <div id="silverlightControlHost">
-               <object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
-                       <param name="source" value="@XAP_FILE@"/>
-                       <param name="onerror" value="onSilverlightError" />
-                       <param name="background" value="white" />
-                       <param name="minRuntimeVersion" value="2.0.31005.0" />
-                       <param name="autoUpgrade" value="true" />
-                       <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
-                       <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
-                       </a>
-               </object>
-               <iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
-    </div>
-</body>
-</html>
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/Respack.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/Respack.cs
deleted file mode 100644 (file)
index 4efcb41..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-//
-// Respack.cs
-//
-// Author:
-//   Ankit Jain (jankit@novell.com)
-//
-// Copyright 2010 Novell, Inc (http://www.novell.com)
-//
-// 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 System.IO;
-using Microsoft.Build.Framework;
-using Microsoft.Build.Tasks;
-using Microsoft.Build.Utilities;
-using Mono.XBuild.Utilities;
-
-namespace Moonlight.Build.Tasks {
-       public class Respack : ToolTask
-       {
-               public override bool Execute ()
-               {
-                       if (!ValidateParameters ()) {
-                               // not generating any resource file
-                               OutputFile = null;
-                               return true;
-                       }
-
-                       return BuildRequired () ? base.Execute () : true;
-               }
-
-               bool BuildRequired ()
-               {
-                       if (!File.Exists (OutputFile.ItemSpec))
-                               return true;
-
-                       DateTime outputFileTime = File.GetLastWriteTime (OutputFile.ItemSpec);
-                       foreach (var res in Resources) {
-                               string file = res.ItemSpec;
-                               if (File.Exists (file) && File.GetLastWriteTime (file) > outputFileTime)
-                                       return true;
-                       }
-
-                       return false;
-               }
-
-               void AddCommandLineCommands (CommandLineBuilderExtension commandLine)
-               {
-                       if (Resources.Length == 0)
-                               return;
-
-                       commandLine.AppendFileNameIfNotNull (OutputFile);
-
-                       commandLine.AppendFileNamesIfNotNull (Resources, " ");
-               }
-
-               protected override string GenerateCommandLineCommands ()
-               {
-                       CommandLineBuilderExtension clbe = new CommandLineBuilderExtension ();
-                       AddCommandLineCommands (clbe);
-                       return clbe.ToString ();
-               }
-
-               protected override string GenerateFullPathToTool ()
-               {
-                       return Path.Combine (ToolPath, ToolExe);
-               }
-
-               protected override bool ValidateParameters()
-               {
-                       return Resources.Length > 0;
-               }
-
-               [Required]
-               [Output]
-               public ITaskItem OutputFile {
-                       get; set;
-               }
-
-               [Required]
-               public ITaskItem[] Resources {
-                       get; set;
-               }
-
-               protected override string ToolName {
-                       get {
-                               return RunningOnWindows ? "respack.bat" : "respack";
-                       }
-               }
-
-                static bool RunningOnWindows {
-                        get {
-                                // Code from Mono.GetOptions/Options.cs
-                                // check for non-Unix platforms - see FAQ for more details
-                                // http://www.mono-project.com/FAQ:_Technical#How_to_detect_the_execution_platform_.3F
-                                int platform = (int) Environment.OSVersion.Platform;
-                                return ((platform != 4) && (platform != 128));
-                        }
-
-                }
-       }
-}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/XamlG.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/XamlG.cs
deleted file mode 100644 (file)
index bacd62d..0000000
+++ /dev/null
@@ -1,378 +0,0 @@
-//
-// XamlG.cs
-//
-// Author:
-//     Michael Hutchinson <mhutchinson@novell.com>
-//     Ankit Jain <jankit@novell.com>
-//
-// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
-// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
-//
-// 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;
-using System.Collections.Generic;
-using System.IO;
-using System.CodeDom;
-using System.CodeDom.Compiler;
-using System.Xml;
-
-using Microsoft.Build.Framework;
-using Microsoft.Build.Utilities;
-
-namespace Moonlight.Build.Tasks {
-       public class XamlG : Task {
-
-               public override bool Execute ()
-               {
-                       if (Sources.Length == 0)
-                               return true;
-
-                       if (OutputFiles == null || Sources.Length != OutputFiles.Length) {
-                               Log.LogError ("Number of OutputFiles must match the number of Source files");
-                               return false;
-                       }
-
-                       var codedom_provider = GetCodeDomProviderForLanguage (Language);
-                       if (codedom_provider == null) {
-                               Log.LogError ("Language {0} not supported for code generation.", Language);
-                               return false;
-                       }
-
-                       for (int i = 0; i < Sources.Length; i ++) {
-                               ITaskItem source_item = Sources [i];
-                               ITaskItem dest_item = OutputFiles [i];
-                               if (!File.Exists (dest_item.ItemSpec) ||
-                                       File.GetLastWriteTime (dest_item.ItemSpec) < File.GetLastWriteTime (source_item.ItemSpec)) {
-                                       Log.LogMessage (MessageImportance.Low, "Generating codebehind accessors for {0}...", source_item.ItemSpec);
-
-                                       string full_source_path = source_item.GetMetadata ("FullPath");
-                                       try {
-                                               if (!XamlGCompiler.GenerateFile (codedom_provider, AssemblyName, full_source_path,
-                                                                               Path.Combine (source_item.GetMetadata ("RelativeDir"),
-                                                                                       Path.GetFileName (source_item.ItemSpec)),
-                                                                               dest_item.ItemSpec, Log)) {
-                                                       Log.LogError ("Error generating {0} from {1}", full_source_path, dest_item.ItemSpec);
-                                                       return false;
-                                               }
-                                       } catch (Exception e) {
-                                               Log.LogError ("Error generating {0} from {1}: {2}", full_source_path, dest_item.ItemSpec, e.Message);
-                                               Log.LogMessage (MessageImportance.Low, "Error generating {0} from {1}: {2}",
-                                                               full_source_path, dest_item.ItemSpec, e.ToString ());
-                                               return false;
-                                       }
-                               }
-                       }
-
-                       return true;
-               }
-
-               CodeDomProvider GetCodeDomProviderForLanguage (string lang)
-               {
-                       switch (lang.ToLower ()) {
-                       case "c#": return new Microsoft.CSharp.CSharpCodeProvider ();
-                       case "vb": return new Microsoft.VisualBasic.VBCodeProvider ();
-                       }
-
-                       return null;
-               }
-
-               [Required]
-               public ITaskItem [] Sources {
-                       get; set;
-               }
-
-               [Required]
-               public string Language {
-                       get; set;
-               }
-
-               [Required]
-               public string AssemblyName {
-                       get; set;
-               }
-
-               [Output]
-               public ITaskItem [] OutputFiles {
-                       get; set;
-               }
-
-               bool HasFileChanged (string source, string dest)
-               {
-                       if (!File.Exists (dest))
-                               return true;
-
-                       FileInfo sourceInfo = new FileInfo (source);
-                       FileInfo destinationInfo = new FileInfo (dest);
-
-                       return !(sourceInfo.Length == destinationInfo.Length &&
-                                       File.GetLastWriteTime(source) <= File.GetLastWriteTime (dest));
-               }
-
-       }
-
-       static class XamlGCompiler
-       {
-               private static bool sl2 = true;
-
-               public static bool GenerateFile (CodeDomProvider provider, string app_name,
-                                                      string xaml_file, string xaml_path_in_project, string out_file, TaskLoggingHelper log)
-               {
-                       XmlDocument xmldoc = new XmlDocument ();
-                       xmldoc.Load (xaml_file);
-
-                       XmlNamespaceManager nsmgr = new XmlNamespaceManager (xmldoc.NameTable);
-                       nsmgr.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
-
-                       XmlNode root = xmldoc.SelectSingleNode ("/*", nsmgr);
-                       if (root == null) {
-                               log.LogError ("{0}: No root node found.", xaml_file);
-                               return false;
-                       }
-
-                       XmlAttribute root_class = root.Attributes ["x:Class"];
-                       if (root_class == null) {
-                               File.WriteAllText (out_file, "");
-                               return true;
-                       }
-
-                       bool is_application = root.LocalName == "Application";
-                       string root_ns;
-                       string root_type;
-                       string root_asm;
-
-                       ParseXmlns (root_class.Value, out root_type, out root_ns, out root_asm);
-
-                       Hashtable names_and_types = GetNamesAndTypes (root, nsmgr);
-//                     Hashtable keys_and_types = GetKeysAndTypes (root, nsmgr);
-
-                       CodeCompileUnit ccu = new CodeCompileUnit ();
-                       CodeNamespace decl_ns = new CodeNamespace (root_ns);
-                       ccu.Namespaces.Add (decl_ns);
-
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Documents"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Input"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media.Animation"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Shapes"));
-                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls.Primitives"));
-
-                       CodeTypeDeclaration decl_type = new CodeTypeDeclaration (root_type);
-                       decl_type.IsPartial = true;
-
-                       decl_ns.Types.Add (decl_type);
-
-                       CodeMemberMethod initcomp = new CodeMemberMethod ();
-                       initcomp.Name = "InitializeComponent";
-                       decl_type.Members.Add (initcomp);
-
-                       if (sl2) {
-                               CodeMemberField field = new CodeMemberField ();
-                               field.Name = "_contentLoaded";
-                               field.Type = new CodeTypeReference (typeof (bool));
-
-                               decl_type.Members.Add (field);
-
-                               CodeConditionStatement is_content_loaded = new CodeConditionStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
-                                               new CodeStatement [] { new CodeMethodReturnStatement () });
-                               initcomp.Statements.Add (is_content_loaded);
-
-                               CodeAssignStatement set_content_loaded = new CodeAssignStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
-                                               new CodePrimitiveExpression (true));
-
-                               initcomp.Statements.Add (set_content_loaded);
-
-                               string component_path = String.Format ("/{0};component/{1}", app_name, xaml_path_in_project);
-                               CodeMethodInvokeExpression load_component = new CodeMethodInvokeExpression (
-                                       new CodeTypeReferenceExpression ("System.Windows.Application"), "LoadComponent",
-                                       new CodeExpression [] { new CodeThisReferenceExpression (),
-                                                               new CodeObjectCreateExpression (new CodeTypeReference ("System.Uri"), new CodeExpression [] {
-                                                                       new CodePrimitiveExpression (component_path),
-                                                                       new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.UriKind"), "Relative") })
-                                       });
-                               initcomp.Statements.Add (load_component);
-                       }
-
-                       if (!is_application) {
-                               foreach (DictionaryEntry entry  in names_and_types) {
-                                       string name = (string) entry.Key;
-                                       CodeTypeReference type = (CodeTypeReference) entry.Value;
-
-                                       CodeMemberField field = new CodeMemberField ();
-
-                                       if (sl2)
-                                               field.Attributes = MemberAttributes.Assembly;
-
-                                       field.Name = name;
-                                       field.Type = type;
-
-                                       decl_type.Members.Add (field);
-
-                                       CodeMethodInvokeExpression find_invoke = new CodeMethodInvokeExpression (
-                                               new CodeThisReferenceExpression(), "FindName",
-                                               new CodeExpression[] { new CodePrimitiveExpression (name) } );
-
-                                       CodeCastExpression cast = new CodeCastExpression (type, find_invoke);
-
-                                       CodeAssignStatement assign = new CodeAssignStatement (
-                                               new CodeVariableReferenceExpression (name), cast);
-
-                                       initcomp.Statements.Add (assign);
-                               }
-                       }
-
-
-                       using (StreamWriter writer = new StreamWriter (out_file)) {
-                               provider.GenerateCodeFromCompileUnit (ccu, writer, new CodeGeneratorOptions ());
-                       }
-
-                       return true;
-               }
-
-               private static Hashtable GetNamesAndTypes (XmlNode root, XmlNamespaceManager nsmgr)
-               {
-                       Hashtable res = new Hashtable ();
-
-                       XmlNodeList names = root.SelectNodes ("//*[@x:Name]", nsmgr);
-                       foreach (XmlNode node in names) {
-
-                               // Don't take the root canvas
-                               if (node == root)
-                                       continue;
-
-                               XmlAttribute attr = node.Attributes ["x:Name"];
-                               string name = attr.Value;
-                               string ns = GetNamespace (node);
-                               string member_type = node.LocalName;
-
-                               if (ns != null)
-                                       member_type = String.Concat (ns, ".", member_type);
-
-                               CodeTypeReference type = new CodeTypeReference (member_type);
-                               if (ns != null)
-                                       type.Options |= CodeTypeReferenceOptions.GlobalReference;
-
-                               res [name] = type;
-                       }
-
-                       return res;
-               }
-
-               /*
-               private static Hashtable GetKeysAndTypes (XmlNode root, XmlNamespaceManager nsmgr)
-               {
-                       Hashtable res = new Hashtable ();
-
-                       XmlNodeList keys = root.SelectNodes ("//*[@x:Key]", nsmgr);
-                       foreach (XmlNode node in keys)  {
-
-                               // Don't take the root canvas
-                               if (node == root)
-                                       continue;
-
-                               XmlAttribute attr = node.Attributes ["x:Key"];
-                               string key = attr.Value;
-                               string ns = GetNamespace (node);
-                               string member_type = node.LocalName;
-
-                               if (ns != null)
-                                       member_type = String.Concat (ns, ".", member_type);
-
-                               res [key] = member_type;
-                       }
-
-                       return res;
-               }
-               */
-
-               internal static string GetNamespace (XmlNode node)
-               {
-                       if (!IsCustom (node.NamespaceURI))
-                               return null;
-
-                       return ParseNamespaceFromXmlns (node.NamespaceURI);
-               }
-
-               private static bool IsCustom (string ns)
-               {
-                       switch (ns) {
-                       case "http://schemas.microsoft.com/winfx/2006/xaml":
-                       case "http://schemas.microsoft.com/winfx/2006/xaml/presentation":
-                       case "http://schemas.microsoft.com/client/2007":
-                               return false;
-                       }
-
-                       return true;
-               }
-
-               private static string ParseNamespaceFromXmlns (string xmlns)
-               {
-                       string type_name = null;
-                       string ns = null;
-                       string asm = null;
-
-                       ParseXmlns (xmlns, out type_name, out ns, out asm);
-
-                       return ns;
-               }
-
-//             private static string ParseTypeFromXmlns (string xmlns)
-//             {
-//                     string type_name = null;
-//                     string ns = null;
-//                     string asm = null;
-//
-//                     ParseXmlns (xmlns, out type_name, out ns, out asm);
-//
-//                     return type_name;
-//             }
-
-               internal static void ParseXmlns (string xmlns, out string type_name, out string ns, out string asm)
-               {
-                       type_name = null;
-                       ns = null;
-                       asm = null;
-
-                       string [] decls = xmlns.Split (';');
-                       foreach (string decl in decls) {
-                               if (decl.StartsWith ("clr-namespace:")) {
-                                       ns = decl.Substring (14, decl.Length - 14);
-                                       continue;
-                               }
-                               if (decl.StartsWith ("assembly=")) {
-                                       asm = decl.Substring (9, decl.Length - 9);
-                                       continue;
-                               }
-                               int nsind = decl.LastIndexOf (".");
-                               if (nsind > 0) {
-                                       ns = decl.Substring (0, nsind);
-                                       type_name = decl.Substring (nsind + 1, decl.Length - nsind - 1);
-                               } else {
-                                       type_name = decl;
-                               }
-                       }
-               }
-       }
-
-}
index 6c5d3683ba48a5bff957bec5a83978ef0de8fe4a..4fe0fee915e66beb6fa475b0b4d11ae92bcdd157 100644 (file)
@@ -12,7 +12,7 @@ CLEAN_FILES += $(STRING_MESSAGES)
 EXTRA_DISTFILES = \
        src/ComponentModel/Strings.resx
        
-VALID_PROFILE := $(filter net_4_0 net_4_5 monotouch monodroid mobile_static, $(PROFILE))
+VALID_PROFILE := $(filter net_4_0 net_4_5 monotouch monodroid xammac mobile_static, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.ComponentModel.Composition.dll
 NO_INSTALL = yes
index 9564b81d88b0fcf436e732a151e8deb00ac5aa09..713754ccdb374241ad47bb325e7d6979becd184d 100644 (file)
@@ -18,7 +18,7 @@ endif
 TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 # This is a .NET 3.5+ assembly
-VALID_PROFILE := $(filter net_2_0 net_4_0 net_4_5 monotouch monodroid mobile_static, $(PROFILE))
+VALID_PROFILE := $(filter net_2_0 net_4_0 net_4_5 monotouch monodroid xammac mobile_static, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.ComponentModel.DataAnnotations.dll
 NO_INSTALL = yes
diff --git a/mcs/class/System.ComponentModel.DataAnnotations/xammac_System.ComponentModel.DataAnnotations.dll.sources b/mcs/class/System.ComponentModel.DataAnnotations/xammac_System.ComponentModel.DataAnnotations.dll.sources
new file mode 100644 (file)
index 0000000..3de14f5
--- /dev/null
@@ -0,0 +1 @@
+#include net_4_5_System.ComponentModel.DataAnnotations.dll.sources
index 22252d68b9f44d0503f3a381dcaf75e5cea7d101..934c3f3cb604938c6b8f35fa7dc982237ba8b639 100644 (file)
@@ -6,6 +6,9 @@ LIBRARY = System.Core.dll
 
 LIB_MCS_FLAGS = -d:INSIDE_SYSCORE -d:LIBC /r:System.dll -unsafe
 
+INTERPRETER_DEP := Mono.Dynamic.Interpreter.dll
+INTERPRETER_DEP_FILE := $(wildcard ../lib/$(PROFILE)/$(INTERPRETER_DEP))
+
 ifneq (2.1, $(FRAMEWORK_VERSION))
 LIB_MCS_FLAGS += -d:NET_3_5 -nowarn:1720
 endif
@@ -14,6 +17,26 @@ ifeq (monodroid, $(PROFILE))
 LIB_MCS_FLAGS += -d:FEATURE_CORE_DLR,FEATURE_REFEMIT,ANDROID
 endif
 
+ifeq (xammac, $(PROFILE))
+LIB_MCS_FLAGS += -d:FEATURE_CORE_DLR,FEATURE_REFEMIT
+endif
+
+ifeq (monotouch, $(PROFILE))
+LIBRARY_USE_INTERMEDIATE_FILE = yes
+
+CYCLIC_DEPS := $(INTERPRETER_DEP)
+CYCLIC_DEP_FILES := $(INTERPRETER_DEP_FILE)
+LIB_MCS_FLAGS += -d:FEATURE_CORE_DLR
+
+ifdef CYCLIC_DEP_FILES
+LIB_MCS_FLAGS += -d:MONO_INTERPRETER -r:$(INTERPRETER_DEP)
+else
+NO_SIGN_ASSEMBLY = yes
+NO_INSTALL = yes
+endif
+
+endif
+
 ifeq (4, $(FRAMEWORK_VERSION_MAJOR))
 LIB_MCS_FLAGS += -d:FEATURE_CORE_DLR,FEATURE_REFEMIT,FEATURE_PDBEMIT
 endif
@@ -30,3 +53,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 include ../../build/library.make
 
+ifdef CYCLIC_DEP_FILES
+$(build_lib): $(INTERPRETER_DEP_FILE)
+endif
+
diff --git a/mcs/class/System.Core/System.Linq.Expressions.Interpret/LambdaCompiler.cs b/mcs/class/System.Core/System.Linq.Expressions.Interpret/LambdaCompiler.cs
new file mode 100644 (file)
index 0000000..23d623a
--- /dev/null
@@ -0,0 +1,47 @@
+// 
+// LambdaCompiler.cs: System.Linq.Expression interpreter entry point
+//
+// 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.Runtime.CompilerServices;
+#if MONO_INTERPRETER
+using Microsoft.Scripting.Generation;
+#endif
+
+namespace System.Linq.Expressions.Compiler
+{
+       static class LambdaCompiler
+       {
+               public static Delegate Compile (LambdaExpression lambda, DebugInfoGenerator debugInfoGenerator)
+               {
+#if MONO_INTERPRETER
+                       return lambda.LightCompile ();
+#else                  
+                       throw new NotSupportedException ("System.Linq.Expression interpreter is missing");
+#endif
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Core/System.Linq.jvm/ChangeLog b/mcs/class/System.Core/System.Linq.jvm/ChangeLog
deleted file mode 100644 (file)
index 24d4b5a..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-2008-09-23  Jb Evain  <jbevain@novell.com>
-
-       * ExpressionInterpreter.cs
-       * Interpreter.cs
-       * Conversion.cs
-       * ExpressionValidator.cs
-       * Math.cs:
-               Integrate changes from db4objects, Inc. The interpreter now
-               passes all linq tests.
diff --git a/mcs/class/System.Core/System.Linq.jvm/Conversion.cs b/mcs/class/System.Core/System.Linq.jvm/Conversion.cs
deleted file mode 100644 (file)
index a3dc754..0000000
+++ /dev/null
@@ -1,463 +0,0 @@
-//
-// Conversion.cs
-//
-// (C) 2008 Mainsoft, Inc. (http://www.mainsoft.com)
-// (C) 2008 db4objects, Inc. (http://www.db4o.com)
-//
-// 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;
-
-namespace System.Linq.jvm {
-
-       class Conversion {
-
-               public static object ConvertPrimitiveUnChecked (Type from, Type to, object value)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (from)) {
-                               case TypeCode.Byte:
-                                       return ConvertByte ((byte) value, to);
-                               case TypeCode.Char:
-                                       return ConvertChar ((char) value, to);
-                               case TypeCode.Decimal:
-                                       return ConvertDecimal ((decimal) value, to);
-                               case TypeCode.Double:
-                                       return ConvertDouble ((double) value, to);
-                               case TypeCode.Int16:
-                                       return ConvertShort ((short) value, to);
-                               case TypeCode.Int32:
-                                       return ConvertInt ((int) value, to);
-                               case TypeCode.Int64:
-                                       return ConvertLong ((long) value, to);
-                               case TypeCode.SByte:
-                                       return ConvertSByte ((sbyte) value, to);
-                               case TypeCode.Single:
-                                       return ConvertFloat ((float) value, to);
-                               case TypeCode.UInt16:
-                                       return ConvertUShort ((ushort) value, to);
-                               case TypeCode.UInt32:
-                                       return ConvertUInt ((uint) value, to);
-                               case TypeCode.UInt64:
-                                       return ConvertULong ((ulong) value, to);
-                               default:
-                                       throw new NotImplementedException ();
-                               }
-                       }
-               }
-
-               static object ConvertByte (byte b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertChar (char b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertDecimal (decimal b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) (short) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertDouble (double b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertShort (short b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertInt (int b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertLong (long b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertSByte (sbyte b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertFloat (float b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertUShort (ushort b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertUInt (uint b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-
-               static object ConvertULong (ulong b, Type to)
-               {
-                       unchecked {
-                               switch (Type.GetTypeCode (to)) {
-                               case TypeCode.Byte:
-                                       return (byte) b;
-                               case TypeCode.Char:
-                                       return (char) b;
-                               case TypeCode.Decimal:
-                                       return (decimal) b;
-                               case TypeCode.Double:
-                                       return (double) b;
-                               case TypeCode.Int16:
-                                       return (short) b;
-                               case TypeCode.Int32:
-                                       return (int) b;
-                               case TypeCode.Int64:
-                                       return (long) b;
-                               case TypeCode.SByte:
-                                       return (sbyte) b;
-                               case TypeCode.Single:
-                                       return (float) b;
-                               case TypeCode.UInt16:
-                                       return (ushort) b;
-                               case TypeCode.UInt32:
-                                       return (uint) b;
-                               case TypeCode.UInt64:
-                                       return (ulong) b;
-                               }
-                               return null;
-                       }
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Linq.jvm/ExpressionInterpreter.cs b/mcs/class/System.Core/System.Linq.jvm/ExpressionInterpreter.cs
deleted file mode 100644 (file)
index 4d550d1..0000000
+++ /dev/null
@@ -1,937 +0,0 @@
-//
-// ExpressionInterpreter.cs
-//
-// (C) 2008 Mainsoft, Inc. (http://www.mainsoft.com)
-// (C) 2008 db4objects, Inc. (http://www.db4o.com)
-// (C) 2010 Novell, Inc. (http://www.novell.com)
-//
-// 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.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Linq.Expressions;
-using System.Reflection;
-
-namespace System.Linq.jvm {
-
-       struct LambdaInfo {
-               public readonly LambdaExpression Lambda;
-               public readonly object [] Arguments;
-
-               public LambdaInfo (LambdaExpression lambda, object [] arguments)
-               {
-                       this.Lambda = lambda;
-                       this.Arguments = arguments;
-               }
-       }
-
-       class HoistedVariableDetector : ExpressionVisitor {
-
-               readonly Dictionary<ParameterExpression, LambdaExpression> parameter_to_lambda =
-                       new Dictionary<ParameterExpression, LambdaExpression> ();
-
-               Dictionary<LambdaExpression, List<ParameterExpression>> hoisted_map;
-
-               LambdaExpression lambda;
-
-               public Dictionary<LambdaExpression, List<ParameterExpression>> Process (LambdaExpression lambda)
-               {
-                       Visit (lambda);
-                       return hoisted_map;
-               }
-
-               protected override void VisitLambda (LambdaExpression lambda)
-               {
-                       this.lambda = lambda;
-                       foreach (var parameter in lambda.Parameters)
-                               parameter_to_lambda [parameter] = lambda;
-                       base.VisitLambda (lambda);
-               }
-
-               protected override void VisitParameter (ParameterExpression parameter)
-               {
-                       if (lambda.Parameters.Contains (parameter))
-                               return;
-
-                       Hoist (parameter);
-               }
-
-               void Hoist (ParameterExpression parameter)
-               {
-                       LambdaExpression lambda;
-                       if (!parameter_to_lambda.TryGetValue (parameter, out lambda))
-                               return;
-
-                       if (hoisted_map == null)
-                               hoisted_map = new Dictionary<LambdaExpression, List<ParameterExpression>> ();
-
-                       List<ParameterExpression> hoisted;
-                       if (!hoisted_map.TryGetValue (lambda, out hoisted)) {
-                               hoisted = new List<ParameterExpression> ();
-                               hoisted_map [lambda] = hoisted;
-                       }
-
-                       hoisted.Add (parameter);
-               }
-       }
-
-
-       class ExpressionInterpreter : ExpressionVisitor {
-
-               readonly Stack<LambdaInfo> lambdas = new Stack<LambdaInfo> ();
-               readonly Stack<object> stack = new Stack<object> ();
-
-               readonly Dictionary<LambdaExpression, List<ParameterExpression>> hoisted_map;
-               readonly Dictionary<ParameterExpression, object> hoisted_values;
-
-               void Push (object value)
-               {
-                       stack.Push (value);
-               }
-
-               object Pop ()
-               {
-                       return stack.Pop ();
-               }
-
-               public ExpressionInterpreter (LambdaExpression lambda)
-               {
-                       hoisted_map = new HoistedVariableDetector ().Process (lambda);
-
-                       if (hoisted_map != null)
-                               hoisted_values = new Dictionary<ParameterExpression, object> ();
-               }
-
-               private void VisitCoalesce (BinaryExpression binary)
-               {
-                       Visit (binary.Left);
-
-                       var left = Pop ();
-
-                       if (left == null) {
-                               Visit (binary.Right);
-                               return;
-                       }
-
-                       if (binary.Conversion == null) {
-                               Push (left);
-                               return;
-                       }
-
-                       Push (Invoke (binary.Conversion.Compile (this), new [] { left }));
-               }
-
-               void VisitAndAlso (BinaryExpression binary)
-               {
-                       object left = null;
-                       object right = null;
-
-                       Visit (binary.Left);
-
-                       left = Pop ();
-
-                       if (left == null || ((bool) left)) {
-                               Visit (binary.Right);
-                               right = Pop ();
-                       }
-
-                       Push (Math.And (left, right));
-               }
-
-               void VisitUserDefinedAndAlso (BinaryExpression binary)
-               {
-                       object left = null;
-                       object right = null;
-
-                       Visit (binary.Left);
-
-                       left = Pop ();
-
-                       if (InvokeFalseOperator (binary, left)) {
-                               Push (left);
-                               return;
-                       }
-
-                       Visit (binary.Right);
-                       right = Pop ();
-
-                       if (binary.IsLiftedToNull && right == null) {
-                               Push (null);
-                               return;
-                       }
-
-                       Push (InvokeMethod (binary.Method, null, new [] { left, right }));
-               }
-
-               static bool InvokeTrueOperator (BinaryExpression binary, object target)
-               {
-                       return (bool) InvokeMethod (GetTrueOperator (binary), null, new [] { target });
-               }
-
-               static bool InvokeFalseOperator (BinaryExpression binary, object target)
-               {
-                       return (bool) InvokeMethod (GetFalseOperator (binary), null, new [] { target });
-               }
-
-               static MethodInfo GetFalseOperator (BinaryExpression binary)
-               {
-                       return Expression.GetFalseOperator (binary.Left.Type.GetNotNullableType ());
-               }
-
-               static MethodInfo GetTrueOperator (BinaryExpression binary)
-               {
-                       return Expression.GetTrueOperator (binary.Left.Type.GetNotNullableType ());
-               }
-
-               void VisitOrElse (BinaryExpression binary)
-               {
-                       object left = null;
-                       object right = null;
-
-                       Visit (binary.Left);
-                       left = Pop ();
-
-                       if (left == null || !((bool) left)) {
-                               Visit (binary.Right);
-                               right = Pop ();
-                       }
-
-                       Push (Math.Or (left, right));
-               }
-
-               void VisitUserDefinedOrElse (BinaryExpression binary)
-               {
-                       object left = null;
-                       object right = null;
-
-                       Visit (binary.Left);
-                       left = Pop ();
-
-                       if (InvokeTrueOperator (binary, left)) {
-                               Push (left);
-                               return;
-                       }
-
-                       Visit (binary.Right);
-                       right = Pop ();
-
-                       if (binary.IsLiftedToNull && right == null) {
-                               Push (null);
-                               return;
-                       }
-
-                       Push (InvokeMethod (binary.Method, null, new [] { left, right }));
-               }
-
-               void VisitLogicalBinary (BinaryExpression binary)
-               {
-                       Visit (binary.Left);
-                       Visit (binary.Right);
-
-                       var right = Pop ();
-                       var left = Pop ();
-
-                       Push (Math.Evaluate (left, right, binary.Type, binary.NodeType));
-               }
-
-               void VisitArithmeticBinary (BinaryExpression binary)
-               {
-                       Visit (binary.Left);
-                       Visit (binary.Right);
-
-                       if (IsNullBinaryLifting (binary))
-                               return;
-
-                       var right = Pop ();
-                       var left = Pop ();
-
-                       switch (binary.NodeType) {
-                       case ExpressionType.RightShift:
-                               Push (Math.RightShift (left, Convert.ToInt32 (right), Type.GetTypeCode (binary.Type.GetNotNullableType ())));
-                               return;
-                       case ExpressionType.LeftShift:
-                               Push (Math.LeftShift (left, Convert.ToInt32 (right), Type.GetTypeCode (binary.Type.GetNotNullableType ())));
-                               return;
-                       default:
-                               Push (Math.Evaluate (left, right, binary.Type, binary.NodeType));
-                               break;
-                       }
-               }
-
-               bool IsNullRelationalBinaryLifting (BinaryExpression binary)
-               {
-                       var right = Pop ();
-                       var left = Pop ();
-
-                       if (binary.IsLifted && (left == null || right == null)) {
-                               if (binary.IsLiftedToNull) {
-                                       Push (null);
-                                       return true;
-                               }
-
-                               switch (binary.NodeType) {
-                               case ExpressionType.Equal:
-                                       Push (BinaryEqual (binary, left, right));
-                                       break;
-                               case ExpressionType.NotEqual:
-                                       Push (BinaryNotEqual (binary, left, right));
-                                       break;
-                               default:
-                                       Push (false);
-                                       break;
-                               }
-
-                               return true;
-                       }
-
-                       Push (left);
-                       Push (right);
-
-                       return false;
-               }
-
-               void VisitRelationalBinary (BinaryExpression binary)
-               {
-                       Visit (binary.Left);
-                       Visit (binary.Right);
-
-                       if (IsNullRelationalBinaryLifting (binary))
-                               return;
-
-                       var right = Pop ();
-                       var left = Pop ();
-
-                       switch (binary.NodeType) {
-                       case ExpressionType.Equal:
-                               Push (BinaryEqual (binary, left, right));
-                               return;
-                       case ExpressionType.NotEqual:
-                               Push (BinaryNotEqual (binary, left, right));
-                               return;
-                       case ExpressionType.LessThan:
-                               Push (Comparer<object>.Default.Compare (left, right) < 0);
-                               return;
-                       case ExpressionType.LessThanOrEqual:
-                               Push (Comparer<object>.Default.Compare (left, right) <= 0);
-                               return;
-                       case ExpressionType.GreaterThan:
-                               Push (Comparer<object>.Default.Compare (left, right) > 0);
-                               return;
-                       case ExpressionType.GreaterThanOrEqual:
-                               Push (Comparer<object>.Default.Compare (left, right) >= 0);
-                               return;
-                       }
-               }
-
-               void VisitLogicalShortCircuitBinary (BinaryExpression binary)
-               {
-                       switch (binary.NodeType) {
-                       case ExpressionType.AndAlso:
-                               VisitAndAlso (binary);
-                               return;
-                       case ExpressionType.OrElse:
-                               VisitOrElse (binary);
-                               return;
-                       }
-               }
-
-               void VisitArrayIndex (BinaryExpression binary)
-               {
-                       Visit (binary.Left);
-                       var left = Pop ();
-                       Visit (binary.Right);
-                       var right = Pop ();
-
-                       Push (((Array) left).GetValue ((int) right));
-               }
-
-               bool IsNullBinaryLifting (BinaryExpression binary)
-               {
-                       var right = Pop ();
-                       var left = Pop ();
-
-                       if (binary.IsLifted && (right == null || left == null)) {
-                               if (binary.IsLiftedToNull)
-                                       Push (null);
-                               else
-                                       Push (GetDefaultValue (binary.Type));
-
-                               return true;
-                       }
-
-                       Push (left);
-                       Push (right);
-
-                       return false;
-               }
-
-               static object GetDefaultValue (Type type)
-               {
-                       var array = (Array) Array.CreateInstance (type, 1);
-                       return array.GetValue (0);
-               }
-
-               void VisitUserDefinedBinary (BinaryExpression binary)
-               {
-                       switch (binary.NodeType) {
-                       case ExpressionType.AndAlso:
-                       case ExpressionType.OrElse:
-                               VisitUserDefinedLogicalShortCircuitBinary (binary);
-                               return;
-                       case ExpressionType.Equal:
-                       case ExpressionType.NotEqual:
-                               VisitUserDefinedRelationalBinary (binary);
-                               return;
-                       default:
-                               VisitUserDefinedCommonBinary (binary);
-                               return;
-                       }
-               }
-
-               void VisitUserDefinedLogicalShortCircuitBinary (BinaryExpression binary)
-               {
-                       switch (binary.NodeType) {
-                       case ExpressionType.AndAlso:
-                               VisitUserDefinedAndAlso (binary);
-                               return;
-                       case ExpressionType.OrElse:
-                               VisitUserDefinedOrElse (binary);
-                               return;
-                       }
-               }
-
-               void VisitUserDefinedRelationalBinary (BinaryExpression binary)
-               {
-                       Visit (binary.Left);
-                       Visit (binary.Right);
-
-                       if (IsNullRelationalBinaryLifting (binary))
-                               return;
-
-                       var right = Pop ();
-                       var left = Pop ();
-
-                       Push (InvokeBinary (binary, left, right));
-               }
-
-               void VisitUserDefinedCommonBinary (BinaryExpression binary)
-               {
-                       Visit (binary.Left);
-                       Visit (binary.Right);
-
-                       if (IsNullBinaryLifting (binary))
-                               return;
-
-                       var right = Pop ();
-                       var left = Pop ();
-
-                       Push (InvokeBinary (binary, left, right));
-               }
-
-               object InvokeBinary (BinaryExpression binary, object left, object right)
-               {
-                       return InvokeMethod (binary.Method, null, new [] { left, right });
-               }
-
-               bool BinaryEqual (BinaryExpression binary, object left, object right)
-               {
-                       if (typeof (ValueType).IsAssignableFrom (binary.Right.Type))
-                               return ValueType.Equals (left, right);
-                       else
-                               return left == right;
-               }
-
-               bool BinaryNotEqual (BinaryExpression binary, object left, object right)
-               {
-                       if (typeof (ValueType).IsAssignableFrom (binary.Right.Type))
-                               return !ValueType.Equals (left, right);
-                       else
-                               return left != right;
-               }
-
-               protected override void VisitBinary (BinaryExpression binary)
-               {
-                       if (binary.Method != null) {
-                               VisitUserDefinedBinary (binary);
-                               return;
-                       }
-
-                       switch (binary.NodeType) {
-                       case ExpressionType.ArrayIndex:
-                               VisitArrayIndex (binary);
-                               return;
-                       case ExpressionType.Coalesce:
-                               VisitCoalesce (binary);
-                               return;
-                       case ExpressionType.AndAlso:
-                       case ExpressionType.OrElse:
-                               VisitLogicalShortCircuitBinary (binary);
-                               return;
-                       case ExpressionType.Equal:
-                       case ExpressionType.NotEqual:
-                       case ExpressionType.GreaterThan:
-                       case ExpressionType.GreaterThanOrEqual:
-                       case ExpressionType.LessThan:
-                       case ExpressionType.LessThanOrEqual:
-                               VisitRelationalBinary (binary);
-                               return;
-                       case ExpressionType.And:
-                       case ExpressionType.Or:
-                               VisitLogicalBinary (binary);
-                               return;
-                       case ExpressionType.Power:
-                       case ExpressionType.Add:
-                       case ExpressionType.AddChecked:
-                       case ExpressionType.Divide:
-                       case ExpressionType.ExclusiveOr:
-                       case ExpressionType.LeftShift:
-                       case ExpressionType.Modulo:
-                       case ExpressionType.Multiply:
-                       case ExpressionType.MultiplyChecked:
-                       case ExpressionType.RightShift:
-                       case ExpressionType.Subtract:
-                       case ExpressionType.SubtractChecked:
-                               VisitArithmeticBinary (binary);
-                               return;
-                       }
-               }
-
-               void VisitTypeAs (UnaryExpression unary)
-               {
-                       Visit (unary.Operand);
-
-                       var value = Pop ();
-                       if (value == null || !Math.IsType (unary.Type, value))
-                               Push (null);
-                       else
-                               Push (value);
-               }
-
-               void VisitArrayLength (UnaryExpression unary)
-               {
-                       Visit (unary.Operand);
-
-                       var array = (Array) Pop ();
-                       Push (array.Length);
-               }
-
-               void VisitConvert (UnaryExpression unary)
-               {
-                       if (unary.NodeType == ExpressionType.ConvertChecked)
-                               VisitConvertChecked (unary);
-                       else
-                               VisitConvertUnchecked (unary);
-               }
-
-               void VisitConvertChecked (UnaryExpression unary)
-               {
-                       VisitConvert (unary, Math.ConvertToTypeChecked);
-               }
-
-               void VisitConvertUnchecked (UnaryExpression unary)
-               {
-                       VisitConvert (unary, Math.ConvertToTypeUnchecked);
-               }
-
-               void VisitConvert (UnaryExpression unary, Func<object, Type, Type, object> converter)
-               {
-                       Visit (unary.Operand);
-                       Push (converter (Pop (), unary.Operand.Type, unary.Type));
-               }
-
-               bool IsNullUnaryLifting (UnaryExpression unary)
-               {
-                       var value = Pop ();
-
-                       if (unary.IsLifted && value == null) {
-                               if (unary.IsLiftedToNull) {
-                                       Push (null);
-                                       return true;
-                               } else {
-                                       throw new InvalidOperationException ();
-                               }
-                       }
-
-                       Push (value);
-                       return false;
-               }
-
-               void VisitQuote (UnaryExpression unary)
-               {
-                       Push (unary.Operand);
-               }
-
-               void VisitUserDefinedUnary (UnaryExpression unary)
-               {
-                       Visit (unary.Operand);
-
-                       if (IsNullUnaryLifting (unary))
-                               return;
-
-                       var value = Pop ();
-
-                       Push (InvokeUnary (unary, value));
-               }
-
-               object InvokeUnary (UnaryExpression unary, object value)
-               {
-                       return InvokeMethod (unary.Method, null, new [] { value });
-               }
-
-               void VisitArithmeticUnary (UnaryExpression unary)
-               {
-                       Visit (unary.Operand);
-
-                       if (IsNullUnaryLifting (unary))
-                               return;
-
-                       var value = Pop ();
-
-                       switch (unary.NodeType) {
-                       case ExpressionType.Not:
-                               if (unary.Type.GetNotNullableType () == typeof (bool))
-                                       Push (!Convert.ToBoolean (value));
-                               else
-                                       Push (~Convert.ToInt32 (value));
-                               return;
-                       case ExpressionType.Negate:
-                               Push (Math.Negate (value, Type.GetTypeCode (unary.Type.GetNotNullableType ())));
-                               return;
-                       case ExpressionType.NegateChecked:
-                               Push (Math.NegateChecked (value, Type.GetTypeCode (unary.Type.GetNotNullableType ())));
-                               return;
-                       case ExpressionType.UnaryPlus:
-                               Push (value);
-                               return;
-                       }
-               }
-
-               protected override void VisitUnary (UnaryExpression unary)
-               {
-                       if (unary.Method != null) {
-                               VisitUserDefinedUnary (unary);
-                               return;
-                       }
-
-                       switch (unary.NodeType) {
-                       case ExpressionType.Quote:
-                               VisitQuote (unary);
-                               return;
-                       case ExpressionType.TypeAs:
-                               VisitTypeAs (unary);
-                               return;
-                       case ExpressionType.ArrayLength:
-                               VisitArrayLength (unary);
-                               return;
-                       case ExpressionType.Convert:
-                       case ExpressionType.ConvertChecked:
-                               VisitConvert (unary);
-                               return;
-                       case ExpressionType.Negate:
-                       case ExpressionType.NegateChecked:
-                       case ExpressionType.Not:
-                       case ExpressionType.UnaryPlus:
-                               VisitArithmeticUnary (unary);
-                               return;
-                       default:
-                               throw new NotImplementedException (unary.NodeType.ToString ());
-                       }
-               }
-
-               protected override void VisitNew (NewExpression nex)
-               {
-                       if (nex.Constructor == null)
-                               Push (Activator.CreateInstance (nex.Type));
-                       else
-                               Push (InvokeConstructor (nex.Constructor, VisitListExpressions (nex.Arguments)));
-               }
-
-               static object InvokeConstructor (ConstructorInfo constructor, object [] arguments)
-               {
-                       try {
-                               return constructor.Invoke (arguments);
-                       } catch (TargetInvocationException e) {
-                               throw e.InnerException;
-                       }
-               }
-
-               protected override void VisitTypeIs (TypeBinaryExpression type)
-               {
-                       Visit (type.Expression);
-                       Push (Math.IsType (type.TypeOperand, Pop ()));
-               }
-
-               void VisitMemberInfo (MemberInfo mi)
-               {
-                       mi.OnFieldOrProperty (
-                               field => {
-                                       object target = null;
-                                       if (!field.IsStatic)
-                                               target = Pop ();
-
-                                       Push (field.GetValue (target));
-                               },
-                               property => {
-                                       object target = null;
-                                       var getter = property.GetGetMethod (true);
-                                       if (!getter.IsStatic)
-                                               target = Pop ();
-
-                                       Push (property.GetValue (target, null));
-                               });
-               }
-
-               protected override void VisitMemberAccess (MemberExpression member)
-               {
-                       Visit (member.Expression);
-                       VisitMemberInfo (member.Member);
-               }
-
-               protected override void VisitNewArray (NewArrayExpression newArray)
-               {
-                       switch (newArray.NodeType) {
-                       case ExpressionType.NewArrayInit:
-                               VisitNewArrayInit (newArray);
-                               return;
-                       case ExpressionType.NewArrayBounds:
-                               VisitNewArrayBounds (newArray);
-                               return;
-                       }
-
-                       throw new NotSupportedException ();
-               }
-
-               void VisitNewArrayBounds (NewArrayExpression newArray)
-               {
-                       var lengths = new int [newArray.Expressions.Count];
-                       for (int i = 0; i < lengths.Length; i++) {
-                               Visit (newArray.Expressions [i]);
-                               lengths [i] = (int) Pop ();
-                       }
-
-                       Push (Array.CreateInstance (newArray.Type.GetElementType (), lengths));
-               }
-
-               void VisitNewArrayInit (NewArrayExpression newArray)
-               {
-                       var array = Array.CreateInstance (
-                               newArray.Type.GetElementType (),
-                               newArray.Expressions.Count);
-
-                       for (int i = 0; i < array.Length; i++) {
-                               Visit (newArray.Expressions [i]);
-                               array.SetValue (Pop (), i);
-                       }
-
-                       Push (array);
-               }
-
-               protected override void VisitConditional (ConditionalExpression conditional)
-               {
-                       Visit (conditional.Test);
-
-                       if ((bool) Pop ())
-                               Visit (conditional.IfTrue);
-                       else
-                               Visit (conditional.IfFalse);
-               }
-
-               protected override void VisitMethodCall (MethodCallExpression call)
-               {
-                       object instance = null;
-                       if (call.Object != null) {
-                               Visit (call.Object);
-                               instance = Pop ();
-                       }
-
-                       Push (InvokeMethod (call.Method, instance, VisitListExpressions (call.Arguments)));
-               }
-
-               protected override void VisitParameter (ParameterExpression parameter)
-               {
-                       var info = lambdas.Peek ();
-
-                       var lambda = info.Lambda;
-                       var arguments = info.Arguments;
-
-                       var index = GetParameterIndex (lambda, parameter);
-                       if (index >= 0) {
-                               Push (arguments [index]);
-                               return;
-                       }
-
-                       object value;
-                       if (hoisted_values.TryGetValue (parameter, out value)) {
-                               Push (value);
-                               return;
-                       }
-
-                       throw new ArgumentException ();
-               }
-
-               protected override void VisitConstant (ConstantExpression constant)
-               {
-                       Push (constant.Value);
-               }
-
-               protected override void VisitInvocation (InvocationExpression invocation)
-               {
-                       Visit (invocation.Expression);
-                       Push (Invoke ((Delegate) Pop (), VisitListExpressions (invocation.Arguments)));
-               }
-
-               static object Invoke (Delegate dlg, object [] arguments)
-               {
-                       return InvokeMethod (dlg.Method, dlg.Target, arguments);
-               }
-
-               static object InvokeMethod (MethodBase method, object obj, object [] arguments)
-               {
-                       try {
-                               return method.Invoke (obj, arguments);
-                       } catch (TargetInvocationException e) {
-                               throw e.InnerException;
-                       }
-               }
-
-               protected override void VisitMemberListBinding (MemberListBinding binding)
-               {
-                       var value = Pop ();
-                       Push (value);
-                       VisitMemberInfo (binding.Member);
-                       VisitElementInitializerList (binding.Initializers);
-                       Pop (); // pop the member
-                       Push (value); // push the original target
-               }
-
-               protected override void VisitElementInitializer (ElementInit initializer)
-               {
-                       object target = null;
-                       if (!initializer.AddMethod.IsStatic)
-                               target = Pop ();
-
-                       var arguments = VisitListExpressions (initializer.Arguments);
-                       InvokeMethod (initializer.AddMethod, target, arguments);
-
-                       if (!initializer.AddMethod.IsStatic)
-                               Push (target);
-               }
-
-               protected override void VisitMemberMemberBinding (MemberMemberBinding binding)
-               {
-                       var value = Pop ();
-                       Push (value);
-                       VisitMemberInfo (binding.Member);
-                       VisitBindingList (binding.Bindings);
-                       Pop ();
-                       Push (value);
-               }
-
-               protected override void VisitMemberAssignment (MemberAssignment assignment)
-               {
-                       Visit (assignment.Expression);
-
-                       var value = Pop ();
-
-                       assignment.Member.OnFieldOrProperty (
-                               field => {
-                                       object target = null;
-                                       if (!field.IsStatic)
-                                               target = Pop ();
-
-                                       field.SetValue (target, value);
-
-                                       if (!field.IsStatic)
-                                               Push (target);
-                               },
-                               property => {
-                                       object target = null;
-                                       var getter = property.GetGetMethod (true);
-                                       if (!getter.IsStatic)
-                                               target = Pop ();
-
-                                       property.SetValue (target, value, null);
-
-                                       if (!getter.IsStatic)
-                                               Push (target);
-                               });
-               }
-
-               protected override void VisitLambda (LambdaExpression lambda)
-               {
-                       Push (lambda.Compile (this));
-               }
-
-               private object [] VisitListExpressions (ReadOnlyCollection<Expression> collection)
-               {
-                       object [] results = new object [collection.Count];
-                       for (int i = 0; i < results.Length; i++) {
-                               Visit (collection [i]);
-                               results [i] = Pop ();
-                       }
-
-                       return results;
-               }
-
-               void StoreHoistedVariables (LambdaExpression lambda, object [] arguments)
-               {
-                       if (hoisted_map == null)
-                               return;
-
-                       List<ParameterExpression> variables;
-                       if (!hoisted_map.TryGetValue (lambda, out variables))
-                               return;
-
-                       foreach (var variable in variables)
-                               StoreHoistedVariable (variable, lambda, arguments);
-               }
-
-               void StoreHoistedVariable (ParameterExpression variable, LambdaExpression lambda, object [] arguments)
-               {
-                       var index = GetParameterIndex (lambda, variable);
-                       if (index < 0)
-                               return;
-
-                       hoisted_values [variable] = arguments [index];
-               }
-
-               static int GetParameterIndex (LambdaExpression lambda, ParameterExpression parameter)
-               {
-                       return lambda.Parameters.IndexOf (parameter);
-               }
-
-               public object Interpret (LambdaExpression lambda, object [] arguments)
-               {
-                       lambdas.Push (new LambdaInfo (lambda, arguments));
-
-                       StoreHoistedVariables (lambda, arguments);
-
-                       Visit (lambda.Body);
-
-                       lambdas.Pop ();
-
-                       if (lambda.GetReturnType () != typeof (void))
-                               return Pop ();
-
-                       return null;
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Linq.jvm/Math.cs b/mcs/class/System.Core/System.Linq.jvm/Math.cs
deleted file mode 100644 (file)
index b3e322c..0000000
+++ /dev/null
@@ -1,695 +0,0 @@
-//
-// Math.cs
-//
-// (C) 2008 Mainsoft, Inc. (http://www.mainsoft.com)
-// (C) 2008 db4objects, Inc. (http://www.db4o.com)
-//
-// 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.Globalization;
-using System.Linq.Expressions;
-
-namespace System.Linq.jvm {
-       class Math {
-
-               public static object Evaluate (object a, object b, Type t, ExpressionType et)
-               {
-                       TypeCode tc = Type.GetTypeCode (t);
-                       if (tc == TypeCode.Object) {
-                               if (!t.IsNullable ()) {
-                                       throw new NotImplementedException (
-                                               string.Format (
-                                               "Expression with Node type {0} for type {1}",
-                                               t.FullName,
-                                               tc));
-
-                               }
-                               return EvaluateNullable (a, b, Type.GetTypeCode (t.GetGenericArguments () [0]), et);
-                       }
-                       return Evaluate (a, b, tc, et);
-               }
-
-               public static object EvaluateNullable (object a, object b, TypeCode tc, ExpressionType et)
-               {
-                       object o = null;
-                       if (a == null || b == null) {
-                               if (tc != TypeCode.Boolean) {
-                                       return null;
-                               }
-                               switch (et) {
-                               case ExpressionType.And:
-                                       o = And (a, b);
-                                       break;
-                               case ExpressionType.Or:
-                                       o = Or (a, b);
-                                       break;
-                               case ExpressionType.ExclusiveOr:
-                                       o = ExclusiveOr (a, b);
-                                       break;
-                               }
-                       } else {
-                               o = Evaluate (a, b, tc, et);
-                       }
-
-                       return Convert2Nullable (o, tc);
-
-               }
-
-               private static object ExclusiveOr (object a, object b)
-               {
-                       if (a == null || b == null) {
-                               return null;
-                       }
-                       return (bool) a ^ (bool) b;
-               }
-
-               public static object Or (object a, object b)
-               {
-                       if (a == null) {
-                               if (b == null || !((bool) b)) {
-                                       return null;
-                               }
-                               return true;
-                       }
-
-                       if (b == null) {
-                               if (a == null || !((bool) a)) {
-                                       return null;
-                               }
-                               return true;
-                       }
-
-                       return (bool) a || (bool) b;
-               }
-
-               public static object And (object a, object b)
-               {
-                       if (a == null) {
-                               if (b == null || (bool) b) {
-                                       return null;
-                               }
-                               return false;
-                       }
-
-                       if (b == null) {
-                               if (a == null || (bool) a) {
-                                       return null;
-                               }
-                               return false;
-                       }
-
-                       return (bool) a && (bool) b;
-               }
-
-               private static object Convert2Nullable (object o, TypeCode tc)
-               {
-                       if (o == null) {
-                               return null;
-                       }
-                       switch (tc) {
-                       case TypeCode.Char:
-                               return new Nullable<Char> ((Char) o);
-                       case TypeCode.Byte:
-                               return new Nullable<Byte> ((Byte) o);
-                       case TypeCode.Decimal:
-                               return new Nullable<Decimal> ((Decimal) o);
-                       case TypeCode.Double:
-                               return new Nullable<Double> ((Double) o);
-                       case TypeCode.Int16:
-                               return new Nullable<Int16> ((Int16) o);
-                       case TypeCode.Int32:
-                               return new Nullable<Int32> ((Int32) o);
-                       case TypeCode.Int64:
-                               return new Nullable<Int64> ((Int64) o);
-                       case TypeCode.UInt16:
-                               return new Nullable<UInt16> ((UInt16) o);
-                       case TypeCode.UInt32:
-                               return new Nullable<UInt32> ((UInt32) o);
-                       case TypeCode.SByte:
-                               return new Nullable<SByte> ((SByte) o);
-                       case TypeCode.Single:
-                               return new Nullable<Single> ((Single) o);
-                       case TypeCode.Boolean:
-                               return new Nullable<Boolean> ((Boolean) o);
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               public static object Evaluate (object a, object b, TypeCode tc, ExpressionType et)
-               {
-                       switch (tc) {
-                       case TypeCode.Boolean:
-                               return Evaluate (Convert.ToBoolean (a), Convert.ToBoolean (b), et);
-                       case TypeCode.Char:
-                               return Evaluate (Convert.ToChar (a), Convert.ToChar (b), et);
-                       case TypeCode.Byte:
-                               return unchecked ((Byte) Evaluate (Convert.ToByte (a), Convert.ToByte (b), et));
-                       case TypeCode.Decimal:
-                               return Evaluate (Convert.ToDecimal (a), Convert.ToDecimal (b), et);
-                       case TypeCode.Double:
-                               return Evaluate (Convert.ToDouble (a), Convert.ToDouble (b), et);
-                       case TypeCode.Int16:
-                               return unchecked ((Int16) Evaluate (Convert.ToInt16 (a), Convert.ToInt16 (b), et));
-                       case TypeCode.Int32:
-                               return Evaluate (Convert.ToInt32 (a), Convert.ToInt32 (b), et);
-                       case TypeCode.Int64:
-                               return Evaluate (Convert.ToInt64 (a), Convert.ToInt64 (b), et);
-                       case TypeCode.UInt16:
-                               return unchecked ((UInt16) Evaluate (Convert.ToUInt16 (a), Convert.ToUInt16 (b), et));
-                       case TypeCode.UInt32:
-                               return Evaluate (Convert.ToUInt32 (a), Convert.ToUInt32 (b), et);
-                       case TypeCode.UInt64:
-                               return Evaluate (Convert.ToUInt64 (a), Convert.ToUInt64 (b), et);
-                       case TypeCode.SByte:
-                               return unchecked ((SByte) Evaluate (Convert.ToSByte (a), Convert.ToSByte (b), et));
-                       case TypeCode.Single:
-                               return Evaluate (Convert.ToSingle (a), Convert.ToSingle (b), et);
-
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               public static object NegateChecked (object a, TypeCode tc)
-               {
-                       switch (tc) {
-                       case TypeCode.Char:
-                               return checked (-Convert.ToChar (a));
-                       case TypeCode.Byte:
-                               return checked (-Convert.ToByte (a));
-                       case TypeCode.Decimal:
-                               return checked (-Convert.ToDecimal (a));
-                       case TypeCode.Double:
-                               return checked (-Convert.ToDouble (a));
-                       case TypeCode.Int16:
-                               return checked (-Convert.ToInt16 (a));
-                       case TypeCode.Int32:
-                               return checked (-Convert.ToInt32 (a));
-                       case TypeCode.Int64:
-                               return checked (-Convert.ToInt64 (a));
-                       case TypeCode.UInt16:
-                               return checked (-Convert.ToUInt16 (a));
-                       case TypeCode.UInt32:
-                               return checked (-Convert.ToUInt32 (a));
-                       case TypeCode.SByte:
-                               return checked (-Convert.ToSByte (a));
-                       case TypeCode.Single:
-                               return checked (-Convert.ToSingle (a));
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               static object CreateInstance (Type type, params object [] arguments)
-               {
-                       return type.GetConstructor (
-                               (from argument in arguments select argument.GetType ()).ToArray ()).Invoke (arguments);
-               }
-
-               public static object ConvertToTypeChecked (object a, Type fromType, Type toType)
-               {
-                       if (toType.IsNullable ())
-                               return a == null ? a : CreateInstance (toType,
-                                       ConvertToTypeChecked (a, fromType.GetNotNullableType (), toType.GetNotNullableType ()));
-
-                       if (a == null) {
-                               if (!toType.IsValueType)
-                                       return a;
-                               if (fromType.IsNullable ())
-                                       throw new InvalidOperationException ("Nullable object must have a value");
-                       }
-
-                       if (IsType (toType, a)) {
-                               return a;
-                       }
-
-                       if (Expression.IsPrimitiveConversion (fromType, toType))
-                               return Convert.ChangeType (a, toType, CultureInfo.CurrentCulture);
-
-                       throw new NotImplementedException (
-                                                       string.Format ("No Convert defined for type {0} ", toType));
-               }
-
-               public static object ConvertToTypeUnchecked (object a, Type fromType, Type toType)
-               {
-                       if (toType.IsNullable ())
-                               return a == null ? a : CreateInstance (toType,
-                                       ConvertToTypeUnchecked (a, fromType.GetNotNullableType (), toType.GetNotNullableType ()));
-
-                       if (a == null) {
-                               if (!toType.IsValueType)
-                                       return a;
-                               if (fromType.IsNullable ())
-                                       throw new InvalidOperationException ("Nullable object must have a value");
-                       }
-
-                       if (IsType (toType, a))
-                               return a;
-
-                       if (Expression.IsPrimitiveConversion (fromType, toType))
-                               return Conversion.ConvertPrimitiveUnChecked (fromType, toType, a);
-
-                       throw new NotImplementedException (
-                                                       string.Format ("No Convert defined for type {0} ", toType));
-               }
-
-               public static bool IsType (Type t, Object o)
-               {
-                       return t.IsInstanceOfType (o);
-               }
-
-               public static object Negate (object a, TypeCode tc)
-               {
-                       switch (tc) {
-                       case TypeCode.Char:
-                               return unchecked (-Convert.ToChar (a));
-                       case TypeCode.Byte:
-                               return unchecked (-Convert.ToByte (a));
-                       case TypeCode.Decimal:
-                               return unchecked (-Convert.ToDecimal (a));
-                       case TypeCode.Double:
-                               return unchecked (-Convert.ToDouble (a));
-                       case TypeCode.Int16:
-                               return unchecked (-Convert.ToInt16 (a));
-                       case TypeCode.Int32:
-                               return unchecked (-Convert.ToInt32 (a));
-                       case TypeCode.Int64:
-                               return unchecked (-Convert.ToInt64 (a));
-                       case TypeCode.UInt16:
-                               return unchecked (-Convert.ToUInt16 (a));
-                       case TypeCode.UInt32:
-                               return unchecked (-Convert.ToUInt32 (a));
-                       case TypeCode.SByte:
-                               return unchecked (-Convert.ToSByte (a));
-                       case TypeCode.Single:
-                               return unchecked (-Convert.ToSingle (a));
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               public static object RightShift (object a, int n, TypeCode tc)
-               {
-                       switch (tc) {
-                       case TypeCode.Int16:
-                               return Convert.ToInt16 (a) >> n;
-                       case TypeCode.Int32:
-                               return Convert.ToInt32 (a) >> n;
-                       case TypeCode.Int64:
-                               return Convert.ToInt64 (a) >> n;
-                       case TypeCode.UInt16:
-                               return Convert.ToUInt16 (a) >> n;
-                       case TypeCode.UInt32:
-                               return Convert.ToUInt32 (a) >> n;
-                       case TypeCode.UInt64:
-                               return Convert.ToUInt64 (a) >> n;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               public static object LeftShift (object a, int n, TypeCode tc)
-               {
-                       switch (tc) {
-                       case TypeCode.Int16:
-                               return Convert.ToInt16 (a) << n;
-                       case TypeCode.Int32:
-                               return Convert.ToInt32 (a) << n;
-                       case TypeCode.Int64:
-                               return Convert.ToInt64 (a) << n;
-                       case TypeCode.UInt16:
-                               return Convert.ToUInt16 (a) << n;
-                       case TypeCode.UInt32:
-                               return Convert.ToUInt32 (a) << n;
-                       case TypeCode.UInt64:
-                               return Convert.ToUInt64 (a) << n;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Decimal Evaluate (Decimal a, Decimal b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Double Evaluate (Double a, Double b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.Power:
-                               return System.Math.Pow (a, b);
-                       }
-
-                       throw new NotImplementedException ();
-
-               }
-
-               private static Int32 Evaluate (Int16 a, Int16 b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Int32 Evaluate (Int32 a, Int32 b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Int64 Evaluate (Int64 a, Int64 b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Int32 Evaluate (UInt16 a, UInt16 b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked ((UInt16) (a - b));
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static UInt32 Evaluate (UInt32 a, UInt32 b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static UInt64 Evaluate (UInt64 a, UInt64 b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static object Evaluate (Char a, Char b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Int32 Evaluate (SByte a, SByte b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Int32 Evaluate (Byte a, Byte b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static Single Evaluate (Single a, Single b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.Add:
-                               return unchecked (a + b);
-                       case ExpressionType.AddChecked:
-                               return checked (a + b);
-                       case ExpressionType.Subtract:
-                               return unchecked (a - b);
-                       case ExpressionType.SubtractChecked:
-                               return checked (a - b);
-                       case ExpressionType.Multiply:
-                               return unchecked (a * b);
-                       case ExpressionType.MultiplyChecked:
-                               return checked (a * b);
-                       case ExpressionType.Divide:
-                               return a / b;
-                       case ExpressionType.Modulo:
-                               return a % b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-
-               private static bool Evaluate (bool a, bool b, ExpressionType et)
-               {
-                       switch (et) {
-                       case ExpressionType.ExclusiveOr:
-                               return a ^ b;
-                       case ExpressionType.And:
-                               return a & b;
-                       case ExpressionType.Or:
-                               return a | b;
-                       }
-
-                       throw new NotImplementedException ();
-               }
-       }
-}
diff --git a/mcs/class/System.Core/System.Linq.jvm/Runner.cs b/mcs/class/System.Core/System.Linq.jvm/Runner.cs
deleted file mode 100644 (file)
index 31f0210..0000000
+++ /dev/null
@@ -1,227 +0,0 @@
-//
-// Runner.cs
-//
-// (C) 2008 Mainsoft, Inc. (http://www.mainsoft.com)
-// (C) 2008 db4objects, Inc. (http://www.db4o.com)
-// (C) 2010 Novell, Inc. (http://www.novell.com)
-//
-// 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.Linq.Expressions;
-using System.Reflection;
-
-namespace System.Linq.jvm {
-
-       sealed class Runner {
-
-               sealed class VoidTypeMarker {}
-
-               static readonly Type VoidMarker = typeof (VoidTypeMarker);
-               static readonly MethodInfo [] delegates = new MethodInfo [5];
-               const BindingFlags method_flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
-
-               readonly LambdaExpression lambda;
-               readonly ExpressionInterpreter interpreter;
-
-               static Runner ()
-               {
-                       foreach (var method in typeof (Runner).GetMethods (method_flags).Where (m => m.Name == "GetDelegate"))
-                               delegates [method.GetGenericArguments ().Length - 1] = method;
-               }
-
-               public Runner (LambdaExpression lambda)
-               {
-                       this.lambda = lambda;
-               }
-
-               public Runner (LambdaExpression lambda, ExpressionInterpreter interpreter)
-               {
-                       this.lambda = lambda;
-                       this.interpreter = interpreter;
-               }
-
-               public Delegate CreateDelegate ()
-               {
-                       var types = GetGenericSignature ();
-                       var creator = delegates [types.Length - 1].MakeGenericMethod (types);
-
-                       return (Delegate) creator.Invoke (this, new object [0]);
-               }
-
-               Type [] GetGenericSignature ()
-               {
-                       var count = lambda.Parameters.Count;
-                       var types = new Type [count + 1];
-
-                       var return_type = lambda.GetReturnType ();
-                       if (return_type == typeof (void))
-                               return_type = VoidMarker;
-
-                       types [count] = return_type;
-                       for (int i = 0; i < count; i++) {
-                               types [i] = lambda.Parameters [i].Type;
-                       }
-
-                       return types;
-               }
-
-               object Run (object [] arguments)
-               {
-                       var interpreter = this.interpreter ?? new ExpressionInterpreter (lambda);
-
-                       return interpreter.Interpret (lambda, arguments);
-               }
-
-               MethodInfo GetActionRunner (params Type [] types)
-               {
-                       return GetRunner ("ActionRunner", types);
-               }
-
-               MethodInfo GetFuncRunner (params Type [] types)
-               {
-                       return GetRunner ("FuncRunner", types);
-               }
-
-               MethodInfo GetRunner (string name, Type [] type_arguments)
-               {
-                       var method = GetMethod (name, type_arguments.Length);
-                       if (method == null)
-                               throw new InvalidOperationException ();
-
-                       if (type_arguments.Length == 0)
-                               return method;
-
-                       return method.MakeGenericMethod (type_arguments);
-               }
-
-               MethodInfo GetMethod (string name, int parameters)
-               {
-                       foreach (var method in GetType ().GetMethods (method_flags)) {
-                               if (method.Name != name)
-                                       continue;
-
-                               if (method.GetGenericArguments ().Length != parameters)
-                                       continue;
-
-                               return method;
-                       }
-
-                       return null;
-               }
-
-               Delegate CreateDelegate (MethodInfo runner)
-               {
-                       return Delegate.CreateDelegate (lambda.Type, this, runner);
-               }
-
-               // all methods below are called through reflection
-
-               Delegate GetDelegate<TResult> ()
-               {
-                       if (typeof (TResult) == VoidMarker)
-                               return CreateDelegate (GetActionRunner (Type.EmptyTypes));
-
-                       return CreateDelegate (GetFuncRunner (typeof (TResult)));
-               }
-
-               public TResult FuncRunner<TResult> ()
-               {
-                       return (TResult) Run (new object [0]);
-               }
-
-               public void ActionRunner ()
-               {
-                       Run (new object [0]);
-               }
-
-               Delegate GetDelegate<T, TResult> ()
-               {
-                       if (typeof (TResult) == VoidMarker)
-                               return CreateDelegate (GetActionRunner (typeof (T)));
-
-                       return CreateDelegate (GetFuncRunner (typeof (T), typeof (TResult)));
-               }
-
-               public TResult FuncRunner<T, TResult> (T arg)
-               {
-                       return (TResult) Run (new object [] { arg });
-               }
-
-               public void ActionRunner<T> (T arg)
-               {
-                       Run (new object [] { arg });
-               }
-
-               public Delegate GetDelegate<T1, T2, TResult> ()
-               {
-                       if (typeof (TResult) == VoidMarker)
-                               return CreateDelegate (GetActionRunner (typeof (T1), typeof (T2)));
-
-                       return CreateDelegate (GetFuncRunner (typeof (T1), typeof (T2), typeof (TResult)));
-               }
-
-               public TResult FuncRunner<T1, T2, TResult> (T1 arg1, T2 arg2)
-               {
-                       return (TResult) Run (new object [] { arg1, arg2 });
-               }
-
-               public void ActionRunner<T1, T2> (T1 arg1, T2 arg2)
-               {
-                       Run (new object [] { arg1, arg2 });
-               }
-
-               Delegate GetDelegate<T1, T2, T3, TResult> ()
-               {
-                       if (typeof (TResult) == VoidMarker)
-                               return CreateDelegate (GetActionRunner (typeof (T1), typeof (T2), typeof (T3)));
-
-                       return CreateDelegate (GetFuncRunner (typeof (T1), typeof (T2), typeof (T3), typeof (TResult)));
-               }
-
-               public TResult FuncRunner<T1, T2, T3, TResult> (T1 arg1, T2 arg2, T3 arg3)
-               {
-                       return (TResult) Run (new object [] { arg1, arg2, arg3 });
-               }
-
-               public void ActionRunner<T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3)
-               {
-                       Run (new object [] { arg1, arg2, arg3 });
-               }
-
-               Delegate GetDelegate<T1, T2, T3, T4, TResult> ()
-               {
-                       if (typeof (TResult) == VoidMarker)
-                               return CreateDelegate (GetActionRunner (typeof (T1), typeof (T2), typeof (T3), typeof (T4)));
-
-                       return CreateDelegate (GetFuncRunner (typeof (T1), typeof (T2), typeof (T3), typeof (T4), typeof (TResult)));
-               }
-
-               public TResult FuncRunner<T1, T2, T3, T4, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4)
-               {
-                       return (TResult) Run (new object [] { arg1, arg2, arg3, arg4 });
-               }
-
-               public void ActionRunner<T1, T2, T3, T4> (T1 arg1, T2 arg2, T3 arg3, T4 arg4)
-               {
-                       Run (new object [] { arg1, arg2, arg3, arg4 });
-               }
-       }
-}
index 320e7a197b04906f0dbf79bd0b0cee37f93ff037..84458d94a20cbf35f18f66e6a4a7792a2fea490d 100644 (file)
@@ -33,7 +33,7 @@ using System.Linq.Expressions;
 
 namespace System.Runtime.CompilerServices {
 
-#if MONODROID
+#if MOBILE_DYNAMIC
        [Obsolete ("do not use this type", true)]
 #endif
        public class ExecutionScope {
@@ -42,12 +42,12 @@ namespace System.Runtime.CompilerServices {
                public object [] Locals;
                public ExecutionScope Parent;
 
-#if !MONODROID
+#if !MOBILE_DYNAMIC
                internal CompilationContext context;
 #endif
                internal int compilation_unit;
 
-#if !MONODROID
+#if !MOBILE_DYNAMIC
                ExecutionScope (CompilationContext context, int compilation_unit)
                {
                        this.context = context;
@@ -69,7 +69,7 @@ namespace System.Runtime.CompilerServices {
 #endif
                public Delegate CreateDelegate (int indexLambda, object [] locals)
                {
-#if MONODROID
+#if MOBILE_DYNAMIC
                        throw new NotSupportedException ();
 #else
                        return context.CreateDelegate (
@@ -80,7 +80,7 @@ namespace System.Runtime.CompilerServices {
 
                public object [] CreateHoistedLocals ()
                {
-#if MONODROID
+#if MOBILE_DYNAMIC
                        throw new NotSupportedException ();
 #else
                        return context.CreateHoistedLocals (compilation_unit);
@@ -89,7 +89,7 @@ namespace System.Runtime.CompilerServices {
 
                public Expression IsolateExpression (Expression expression, object [] locals)
                {
-#if MONODROID
+#if MOBILE_DYNAMIC
                        throw new NotSupportedException ();
 #else
                        return context.IsolateExpression (this, locals, expression);
index dc47009d415a0d6ab26aaa8ab0d1584bca9ad087..a9257c259bda8e9de351f92828a90d2773c5cf6f 100644 (file)
@@ -103,5 +103,26 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) * value(MonoTests.System.Linq.Expressions.OpClass))",
                                expr.ToString(), "Multiply#13");
                }
+
+               [Test]
+               public void Compile ()
+               {
+                       var left = Expression.Parameter (typeof (int), "l");
+                       var right = Expression.Parameter (typeof (int), "r");
+                       var l = Expression.Lambda<Func<int, int, int>> (
+                               Expression.Multiply (left, right), left, right);
+
+                       var be = l.Body as BinaryExpression;
+                       Assert.IsNotNull (be);
+                       Assert.AreEqual (typeof (int), be.Type);
+                       Assert.IsFalse (be.IsLifted);
+                       Assert.IsFalse (be.IsLiftedToNull);
+
+                       var c = l.Compile ();
+
+                       Assert.AreEqual (36, c (6, 6));
+                       Assert.AreEqual (-1, c (-1, 1));
+                       Assert.AreEqual (-3, c (1, -3));
+               }
        }
 }
index 3d43b2ae9a865e8f99f33afbed53306ad38ebc1e..e0414c3d0fd47e48d58297346e1e633b9fc9318a 100644 (file)
@@ -103,5 +103,26 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) - value(MonoTests.System.Linq.Expressions.OpClass))",
                                expr.ToString(), "Subtract#13");
                }
+
+               [Test]
+               public void CompileSubtract ()
+               {
+                       var left = Expression.Parameter (typeof (int), "l");
+                       var right = Expression.Parameter (typeof (int), "r");
+                       var l = Expression.Lambda<Func<int, int, int>> (
+                               Expression.Subtract (left, right), left, right);
+
+                       var be = l.Body as BinaryExpression;
+                       Assert.IsNotNull (be);
+                       Assert.AreEqual (typeof (int), be.Type);
+                       Assert.IsFalse (be.IsLifted);
+                       Assert.IsFalse (be.IsLiftedToNull);
+
+                       var c = l.Compile ();
+
+                       Assert.AreEqual (0, c (6, 6));
+                       Assert.AreEqual (-2, c (-1, 1));
+                       Assert.AreEqual (4, c (1, -3));
+               }
        }
 }
index bd54b1997605d5c0008ef82808f5b21869660b9e..f5f5034c95c666ebcca899197226b13c3b4d833c 100644 (file)
 ../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReflectionUtils.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs
-
-System.Core/Dummy.cs
-
-System.Runtime.CompilerServices/ExecutionScope.cs
-System.Runtime.CompilerServices/DynamicAttribute.cs
-System.Linq.Expressions/ExpressionTransformer.cs
-System.Linq.Expressions/Extensions.cs
-System.Linq.Expressions/DynamicExpressionVisitor.cs
diff --git a/mcs/class/System.Core/interpreter_System.Core.dll.sources b/mcs/class/System.Core/interpreter_System.Core.dll.sources
new file mode 100644 (file)
index 0000000..5ca0d48
--- /dev/null
@@ -0,0 +1,91 @@
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/BinaryOperationBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/BindingRestrictions.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallInfo.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSite.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteHelpers.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteOps.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/ConvertBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/CreateInstanceBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteIndexBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteMemberBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObject.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObjectBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicObject.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoClass.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoObject.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/GetIndexBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/GetMemberBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/IDynamicMetaObjectProvider.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeMemberBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/RuleCache.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/SetIndexBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/SetMemberBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/UnaryOperationBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/UpdateDelegates.Generated.cs
+
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/BinaryExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/BlockExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/CatchBlock.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ConditionalExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ConstantExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugInfoExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugViewWriter.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/DefaultExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ElementInit.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.DebuggerProxy.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionStringBuilder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionType.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionVisitor.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/GotoExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/IArgumentProvider.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/IndexExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/InvocationExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelTarget.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/LambdaExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ListArgumentProvider.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ListInitExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/LoopExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberAssignment.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberBinding.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberInitExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberListBinding.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberMemberBinding.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/MethodCallExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/NewExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/ParameterExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/RuntimeVariablesExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchCase.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/SymbolDocumentInfo.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/TryExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeBinaryExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeUtils.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/UnaryExpression.cs
+
+../dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.Generated.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Compiler/Set.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolGuids.cs
+
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/CacheDict.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/CollectionExtensions.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/ContractUtils.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/ExceptionFactory.Generated.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/Helpers.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/IRuntimeVariables.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyCollectionBuilder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyDictionary.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReferenceEqualityComparer.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReflectionUtils.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs
+
+System.Linq.Expressions.Interpret/LambdaCompiler.cs
index 28780b7708e3540d2c4d143f724b0967a3e08775..ba66db603d70144b0c00cc7b9b8e793a5d854f54 100644 (file)
@@ -7,6 +7,7 @@ System/TimeZoneInfo.cs
 System/TimeZoneInfo.TransitionTime.cs
 System/TimeZoneNotFoundException.cs
 System/Util.cs
+System.Runtime.CompilerServices/DynamicAttribute.cs
 System.Runtime.CompilerServices/ExecutionScope.cs
 System.Runtime.CompilerServices/ExtensionAttribute.cs
 System.Runtime.CompilerServices/IStrongBox.cs
@@ -98,3 +99,9 @@ Microsoft.Win32.SafeHandles/SafeMemoryMappedFileHandle.cs
 Microsoft.Win32.SafeHandles/SafeMemoryMappedViewHandle.cs
 System.IO/HandleInheritability.cs
 System.Threading.Tasks/TaskExtensions.cs
+System.Linq.Expressions/Extensions.cs
+System.Linq.Expressions/ExpressionTransformer.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Ast/DynamicExpression.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Compiler/Closure.cs
+System.Linq.Expressions/DynamicExpressionVisitor.cs
+
diff --git a/mcs/class/System.Core/mobile_static_System.Core.dll.sources b/mcs/class/System.Core/mobile_static_System.Core.dll.sources
deleted file mode 100644 (file)
index 55e204a..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-#include mobile_System.Core.dll.sources
-#include static_System.Core.dll.sources
-System.Linq.jvm/Conversion.cs
-System.Linq.jvm/ExpressionInterpreter.cs
-System.Linq.jvm/Runner.cs
-System.Linq.jvm/Math.cs
-System/TimeZoneInfo.MonoTouch.cs
index 55e204afd6c732c5b9376e6cc1380e93ae1eedef..fad05a08f1c16d427b2c9476f112a3f9d8585718 100644 (file)
@@ -1,7 +1,3 @@
 #include mobile_System.Core.dll.sources
-#include static_System.Core.dll.sources
-System.Linq.jvm/Conversion.cs
-System.Linq.jvm/ExpressionInterpreter.cs
-System.Linq.jvm/Runner.cs
-System.Linq.jvm/Math.cs
+#include interpreter_System.Core.dll.sources
 System/TimeZoneInfo.MonoTouch.cs
index bb9240f7bf3868625b20ea730300d3c45e5a37f7..65bcfd88012357935606129ced875a54954a3841 100644 (file)
@@ -1,3 +1,4 @@
+#include dynamic_System.Core.dll.sources
 Assembly/AssemblyInfo.cs
 System/Actions.cs
 System/Funcs.cs
@@ -88,126 +89,6 @@ System.IO.Pipes/PipeUnix.cs
 System.IO.Pipes/PipeWin32.cs
 System.IO/HandleInheritability.cs
 
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/BinaryOperationBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/BindingRestrictions.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallInfo.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSite.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteHelpers.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/CallSiteOps.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/ConvertBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/CreateInstanceBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteIndexBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/DeleteMemberBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObject.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicMetaObjectBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicObject.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoClass.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/ExpandoObject.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/GetIndexBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/GetMemberBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/IDynamicMetaObjectProvider.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeMemberBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/RuleCache.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/SetIndexBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/SetMemberBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/UnaryOperationBinder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Actions/UpdateDelegates.Generated.cs
-
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/BinaryExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/BlockExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/CatchBlock.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ConditionalExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ConstantExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugInfoExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/DebugViewWriter.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/DefaultExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/DynamicExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ElementInit.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/Expression.DebuggerProxy.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionStringBuilder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionType.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ExpressionVisitor.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/GotoExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/IArgumentProvider.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/IndexExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/InvocationExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/LabelTarget.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/LambdaExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ListArgumentProvider.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ListInitExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/LoopExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberAssignment.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberBinding.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberInitExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberListBinding.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/MemberMemberBinding.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/MethodCallExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/NewExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/ParameterExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/RuntimeVariablesExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchCase.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/SwitchExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/SymbolDocumentInfo.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/TryExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeBinaryExpression.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeUtils.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Ast/UnaryExpression.cs
-
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/AnalyzedTree.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/AssemblyGen.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/BoundConstants.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/Closure.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/CompilerScope.Storage.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/ConstantCheck.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/DebugInfoGenerator.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/DelegateHelpers.Generated.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/ExpressionQuoter.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/HoistedLocals.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/ILGen.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/KeyedQueue.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LabelInfo.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Address.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Binary.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.ControlFlow.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Expressions.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Generated.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Lambda.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Logical.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Statements.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/LambdaCompiler.Unary.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/OffsetTrackingILGenerator.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/RuntimeVariableList.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/Set.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Bindings.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Generated.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Temps.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolDocumentGenerator.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/SymbolGuids.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Compiler/VariableBinder.cs
-
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/CacheDict.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/CollectionExtensions.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/ContractUtils.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/ExceptionFactory.Generated.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/Helpers.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/IRuntimeVariables.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyCollectionBuilder.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReadOnlyDictionary.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReferenceEqualityComparer.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReflectionUtils.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs
-../dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs
 System.Linq.Parallel/ParallelQueryEnumerator.cs
 System.Linq/OrderedParallelQuery.cs
 System.Linq/ParallelMergeOptions.cs
diff --git a/mcs/class/System.Core/static_System.Core.dll.sources b/mcs/class/System.Core/static_System.Core.dll.sources
deleted file mode 100644 (file)
index 7696cbe..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-System.Linq.Expressions/BinaryExpression.cs
-System.Linq.Expressions/ConditionalExpression.cs
-System.Linq.Expressions/ConstantExpression.cs
-System.Linq.Expressions/ElementInit.cs
-System.Linq.Expressions/EmitContext.cs
-System.Linq.Expressions/Expression.cs
-System.Linq.Expressions/Expression_T.cs
-System.Linq.Expressions/ExpressionPrinter.cs
-System.Linq.Expressions/ExpressionType.cs
-System.Linq.Expressions/ExpressionVisitor.cs
-System.Linq.Expressions/ExpressionTransformer.cs
-System.Linq.Expressions/Extensions.cs
-System.Linq.Expressions/InvocationExpression.cs
-System.Linq.Expressions/LambdaExpression.cs
-System.Linq.Expressions/ListInitExpression.cs
-System.Linq.Expressions/MemberAssignment.cs
-System.Linq.Expressions/MemberBinding.cs
-System.Linq.Expressions/MemberBindingType.cs
-System.Linq.Expressions/MemberExpression.cs
-System.Linq.Expressions/MemberInitExpression.cs
-System.Linq.Expressions/MemberListBinding.cs
-System.Linq.Expressions/MemberMemberBinding.cs
-System.Linq.Expressions/MethodCallExpression.cs
-System.Linq.Expressions/NewArrayExpression.cs
-System.Linq.Expressions/NewExpression.cs
-System.Linq.Expressions/ParameterExpression.cs
-System.Linq.Expressions/TypeBinaryExpression.cs
-System.Linq.Expressions/UnaryExpression.cs
diff --git a/mcs/class/System.Core/xammac_System.Core.dll.sources b/mcs/class/System.Core/xammac_System.Core.dll.sources
new file mode 100644 (file)
index 0000000..7754897
--- /dev/null
@@ -0,0 +1,8 @@
+#include mobile_System.Core.dll.sources
+
+#include dynamic_System.Core.dll.sources
+
+System.Security.Cryptography/AesCryptoServiceProvider.cs
+System.Security.Cryptography/AesManaged.cs
+System.Security.Cryptography/AesTransform.cs
+
index 3f7810f6c0800e5cb2bf72614872797d268f7ca5..dbec9aca65d04c8eb7e15e96e46e4427e0b95fb8 100644 (file)
@@ -1345,7 +1345,7 @@ namespace Test.OracleClient
                                cmd2.ExecuteNonQuery ();
                        }
                        catch(OracleException) {
-                               // ignore if procedure does not exists
+                               // ignore if procedure does not exist
                        }
 
                        Console.WriteLine("  Create table MONO_TEST_TABLE2...");
diff --git a/mcs/class/System.Data.Services.Client/xammac_System.Data.Services.Client.dll.sources b/mcs/class/System.Data.Services.Client/xammac_System.Data.Services.Client.dll.sources
new file mode 100644 (file)
index 0000000..37dc299
--- /dev/null
@@ -0,0 +1 @@
+#include net_4_5_System.Data.Services.Client.dll.sources
index 8255e6456d6a582e6f87ddf5142663675f4fa80d..4a15ce7480d0556d25953d2c57ef2caaf42f0c76 100644 (file)
@@ -31,7 +31,7 @@ LIB_MCS_FLAGS +=      \
        -r:J2SE.Helpers.dll                     \
        $(OTHER_LIB_MCS_FLAGS)
 else 
-MOBILE := $(filter monotouch monodroid mobile mobile_static, $(PROFILE))
+MOBILE := $(filter monotouch monodroid xammac mobile mobile_static, $(PROFILE))
 ifdef MOBILE
 LIB_MCS_FLAGS += \
        -r:Mono.Data.Tds.dll \
diff --git a/mcs/class/System.Data/xammac_System.Data.dll.sources b/mcs/class/System.Data/xammac_System.Data.dll.sources
new file mode 100644 (file)
index 0000000..bbc860b
--- /dev/null
@@ -0,0 +1 @@
+#include mobile_System.Data.dll.sources
index 487bdbcd1604ae2bb5ef9cfb1ae0c37a887b9e1a..87f69ad7d0ff138216d1991b421ab9fa1ec73f4d 100644 (file)
@@ -322,7 +322,7 @@ namespace MonoTests.System.DirectoryServices
                        ds.Filter = "(objectClass=person)";\r
                        result = ds.FindOne();\r
 \r
-                       // Properties that does not exists are not loaded\r
+                       // Properties that do not exist are not loaded\r
                        Assert.AreEqual(result.Properties.Count,3);\r
                        Assert.IsTrue(result.Properties.Contains("cn"));\r
                        Assert.IsTrue(result.Properties.Contains("objectClass"));\r
index 4305b344dec63885a50c717014eae5812a907030..70740170701f4bbdffef8591a21e0d51837d1eb9 100644 (file)
@@ -21,7 +21,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Interactive.Async.dll
 NO_SIGN_ASSEMBLY = yes
index 68291088719336c1be0252505e25d7f19c425e78..c74dccb727189de42a6991875826b4f6b193740b 100644 (file)
@@ -22,7 +22,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Interactive.Providers.dll
 NO_SIGN_ASSEMBLY = yes
index 2d6248e7bad3a0629417f044354180f2e2cad51d..ec5cd5c01df79265c08a7c60f88cc094cd9e9d7a 100644 (file)
@@ -21,7 +21,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Interactive.dll
 NO_SIGN_ASSEMBLY = yes
index 5124d3f6e6c6a472c629c050039ede30640b42e2..eb4b37f3497ccd30311ceb843a6602d7ddaa2ad8 100644 (file)
@@ -23,6 +23,10 @@ ifeq (monodroid, $(PROFILE))
 LIB_MCS_FLAGS += -d:FEATURE_DYNAMIC
 endif
 
+ifeq (xammac, $(PROFILE))
+LIB_MCS_FLAGS += -d:FEATURE_DYNAMIC
+endif
+
 TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 include ../../build/library.make
index 33f87db8f032bea12e6103e809248456c3557133..7bb2496a94d84d2c5962280e783975d8018d09b6 100644 (file)
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Collections.Generic;
+
 namespace System.Net.Http.Headers
 {
        public class AuthenticationHeaderValue : ICloneable
@@ -85,8 +87,23 @@ namespace System.Net.Http.Headers
                public static bool TryParse (string input, out AuthenticationHeaderValue parsedValue)
                {
                        var lexer = new Lexer (input);
-                       var t = lexer.Scan ();
-                       if (t != Token.Type.Token || !(lexer.PeekChar () == ' ' || lexer.PeekChar () == -1)) {
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
+                       parsedValue = null;
+                       return false;
+               }
+
+               internal static bool TryParse (string input, int minimalCount, out List<AuthenticationHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
+
+               static bool TryParseElement (Lexer lexer, out AuthenticationHeaderValue parsedValue, out Token t)
+               {
+                       t = lexer.Scan ();
+                       if (t != Token.Type.Token) {
                                parsedValue = null;
                                return false;
                        }
@@ -95,8 +112,11 @@ namespace System.Net.Http.Headers
                        parsedValue.Scheme = lexer.GetStringValue (t);
 
                        t = lexer.Scan ();
-                       if (t != Token.Type.End)
+                       if (t == Token.Type.Token) {
+                               // TODO: Wrong with multi value parsing
                                parsedValue.Parameter = lexer.GetRemainingStringValue (t.StartPosition);
+                               t = new Token (Token.Type.End, 0, 0);
+                       }
 
                        return true;
                }
diff --git a/mcs/class/System.Net.Http/System.Net.Http.Headers/CollectionParser.cs b/mcs/class/System.Net.Http/System.Net.Http.Headers/CollectionParser.cs
new file mode 100644 (file)
index 0000000..cbaafe0
--- /dev/null
@@ -0,0 +1,117 @@
+//
+// CollectionParser.cs
+//
+// Authors:
+//     Marek Safar  <marek.safar@gmail.com>
+//
+// Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com)
+//
+// 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.Collections.Generic;
+
+namespace System.Net.Http.Headers
+{
+       delegate bool ElementTryParser<T> (Lexer lexer, out T parsedValue, out Token token);
+
+       static class CollectionParser
+       {
+               public static bool TryParse<T> (string input, int minimalCount, ElementTryParser<T> parser, out List<T> result) where T : class
+               {
+                       var lexer = new Lexer (input);
+                       result = new List<T> ();
+
+                       while (true) {
+                               Token token;
+                               T parsedValue;
+                               if (!parser (lexer, out parsedValue, out token))
+                                       return false;
+
+                               if (parsedValue != null)
+                                       result.Add (parsedValue);
+
+                               if (token == Token.Type.SeparatorComma)
+                                       continue;
+
+                               if (token == Token.Type.End) {
+                                       if (minimalCount > result.Count) {
+                                               result = null;
+                                               return false;
+                                       }
+                                               
+                                       return true;
+                               }
+
+                               result = null;
+                               return false;
+                       }
+               }
+
+               public static bool TryParse (string input, int minimalCount, out List<string> result)
+               {
+                       return TryParse (input, minimalCount, TryParseStringElement, out result);
+               }
+
+               public static bool TryParseRepetition (string input, int minimalCount, out List<string> result)
+               {
+                       return TryParseRepetition (input, minimalCount, TryParseStringElement, out result);
+               }
+
+               static bool TryParseStringElement (Lexer lexer, out string parsedValue, out Token t)
+               {
+                       t = lexer.Scan ();
+                       if (t == Token.Type.Token) {
+                               parsedValue = lexer.GetStringValue (t);
+                               if (parsedValue.Length == 0)
+                                       parsedValue = null;
+
+                               t = lexer.Scan ();
+                       } else {
+                               parsedValue = null;
+                       }
+
+                       return true;
+               }
+
+               public static bool TryParseRepetition<T> (string input, int minimalCount, ElementTryParser<T> parser, out List<T> result) where T : class
+               {
+                       var lexer = new Lexer (input);
+                       result = new List<T> ();
+
+                       while (true) {
+                               Token token;
+                               T parsedValue;
+                               if (!parser (lexer, out parsedValue, out token))
+                                       return false;
+
+                               if (parsedValue != null)
+                                       result.Add (parsedValue);
+
+                               if (token == Token.Type.End) {
+                                       if (minimalCount > result.Count)
+                                               return false;
+                                               
+                                       return true;
+                               }
+                       }
+               }
+       }
+}
\ No newline at end of file
index a4d1ae275b478decfcf16103b66b7d4819a6e461..9dd41b3d330bddb745042e56b29ec59b05f72a83 100644 (file)
@@ -394,7 +394,7 @@ namespace System.Net.Http.Headers
 
                        switch (t.Kind) {
                        case Token.Type.SeparatorSemicolon:
-                               if (!NameValueHeaderValue.TryParseParameters (lexer, out parameters))
+                               if (!NameValueHeaderValue.TryParseParameters (lexer, out parameters, out t) || t != Token.Type.End)
                                        return false;
                                break;
                        case Token.Type.End:
index 9b10983bbfcdf953fa59b330d45c204e45ef5052..8c255cfaede359f304c17c79bd966512b24dca96 100644 (file)
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Collections.Generic;
+
 namespace System.Net.Http.Headers
 {
        public class EntityTagHeaderValue : ICloneable
@@ -85,14 +87,32 @@ namespace System.Net.Http.Headers
 
                public static bool TryParse (string input, out EntityTagHeaderValue parsedValue)
                {
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
                        parsedValue = null;
+                       return false;
+               }
 
-                       var lexer = new Lexer (input);
-                       var t = lexer.Scan ();
+               static bool TryParseElement (Lexer lexer, out EntityTagHeaderValue parsedValue, out Token t)
+               {
+                       parsedValue = null;
+
+                       t = lexer.Scan ();
                        bool is_weak = false;
 
                        if (t == Token.Type.Token) {
-                               if (lexer.GetStringValue (t) != "W" || lexer.PeekChar () != '/')
+                               var s = lexer.GetStringValue (t);
+                               if (s == "*") {
+                                       parsedValue = any;
+
+                                       t = lexer.Scan ();
+                                       return true;
+                               }
+
+                               if (s != "W" || lexer.PeekChar () != '/')
                                        return false;
 
                                is_weak = true;
@@ -103,15 +123,20 @@ namespace System.Net.Http.Headers
                        if (t != Token.Type.QuotedString)
                                return false;
 
-                       if (lexer.Scan () != Token.Type.End)
-                               return false;
-
                        parsedValue = new EntityTagHeaderValue ();
                        parsedValue.Tag = lexer.GetStringValue (t);
                        parsedValue.IsWeak = is_weak;
+
+                       t = lexer.Scan ();
+
                        return true;
                }
 
+               internal static bool TryParse (string input, int minimalCount, out List<EntityTagHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
+
                public override string ToString ()
                {
                        return IsWeak ?
index 3772180e52bc0ea9f617d6c522cf4df995bac762..6337319ea1e135c71821f74c93cd561f5219b612 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Marek Safar  <marek.safar@gmail.com>
 //
-// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
+// Copyright (C) 2011, 2014 Xamarin Inc (http://www.xamarin.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -32,6 +32,7 @@ using System.Collections.Generic;
 namespace System.Net.Http.Headers
 {
        delegate bool TryParseDelegate<T> (string value, out T result);
+       delegate bool TryParseListDelegate<T> (string value, int minimalCount, out List<T> result);
 
        abstract class HeaderInfo
        {
@@ -89,6 +90,32 @@ namespace System.Net.Http.Headers
                        }
                }
 
+               class CollectionHeaderTypeInfo<T, U> : HeaderTypeInfo<T, U> where U : class
+               {
+                       readonly int minimalCount;
+                       TryParseListDelegate<T> parser;
+
+                       public CollectionHeaderTypeInfo (string name, TryParseListDelegate<T> parser, HttpHeaderKind headerKind, int minimalCount)
+                               : base (name, null, headerKind)
+                       {
+                               this.parser = parser;
+                               this.minimalCount = minimalCount;
+                               AllowsMany = true;
+                       }
+
+                       public override bool TryParse (string value, out object result)
+                       {
+                               List<T> tresult;
+                               if (!parser (value, minimalCount, out tresult)) {
+                                       result = null;
+                                       return false;
+                               }
+
+                               result = tresult;
+                               return true;
+                       }
+               }
+
                public bool AllowsMany;
                public readonly HttpHeaderKind HeaderKind;
                public readonly string Name;
@@ -104,18 +131,12 @@ namespace System.Net.Http.Headers
                        return new HeaderTypeInfo<T, object> (name, parser, headerKind);
                }
 
-               public static HeaderInfo CreateMulti<T> (string name, TryParseDelegate<T> parser, HttpHeaderKind headerKind) where T : class
-               {
-                       return new HeaderTypeInfo<T, T> (name, parser, headerKind) {
-                               AllowsMany = true,
-                       };
-               }
-
-               public static HeaderInfo CreateMultiList<T> (string name, TryParseDelegate<List<T>> parser, HttpHeaderKind headerKind) where T : class
+               //
+               // Headers with #rule for defining lists of elements or *rule for defining occurences of elements
+               //
+               public static HeaderInfo CreateMulti<T> (string name, TryParseListDelegate<T> elementParser, HttpHeaderKind headerKind, int minimalCount = 1) where T : class
                {
-                       return new HeaderTypeInfo<List<T>, T> (name, parser, headerKind) {
-                               AllowsMany = true,
-                       };
+                       return new CollectionHeaderTypeInfo<T, T> (name, elementParser, headerKind, minimalCount);
                }
 
                public object CreateCollection (HttpHeaders headers)
index a36652ce4eb4e3379bd626abd17c3473056a6b2c..ffef647b5ee5a76029019d606acdb8e3e8c250e4 100644 (file)
@@ -90,14 +90,14 @@ namespace System.Net.Http.Headers
                                HeaderInfo.CreateMulti<StringWithQualityHeaderValue> ("Accept-Charset", StringWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
                                HeaderInfo.CreateMulti<StringWithQualityHeaderValue> ("Accept-Encoding", StringWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
                                HeaderInfo.CreateMulti<StringWithQualityHeaderValue> ("Accept-Language", StringWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
-                               HeaderInfo.CreateMulti<string> ("Accept-Ranges", Parser.Token.TryParse, HttpHeaderKind.Response),
+                               HeaderInfo.CreateMulti<string> ("Accept-Ranges", CollectionParser.TryParse, HttpHeaderKind.Response),
                                HeaderInfo.CreateSingle<TimeSpan> ("Age", Parser.TimeSpanSeconds.TryParse, HttpHeaderKind.Response),
-                               HeaderInfo.CreateMulti<string> ("Allow", Parser.Token.TryParse, HttpHeaderKind.Content),
+                               HeaderInfo.CreateMulti<string> ("Allow", CollectionParser.TryParse, HttpHeaderKind.Content, 0),
                                HeaderInfo.CreateSingle<AuthenticationHeaderValue> ("Authorization", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Request),
                                HeaderInfo.CreateSingle<CacheControlHeaderValue> ("Cache-Control", CacheControlHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
-                               HeaderInfo.CreateMulti<string> ("Connection", Parser.Token.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
-                               HeaderInfo.CreateMulti<string> ("Content-Encoding", Parser.Token.TryParse, HttpHeaderKind.Content),
-                               HeaderInfo.CreateMulti<string> ("Content-Language", Parser.Token.TryParse, HttpHeaderKind.Content),
+                               HeaderInfo.CreateMulti<string> ("Connection", CollectionParser.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
+                               HeaderInfo.CreateMulti<string> ("Content-Encoding", CollectionParser.TryParse, HttpHeaderKind.Content),
+                               HeaderInfo.CreateMulti<string> ("Content-Language", CollectionParser.TryParse, HttpHeaderKind.Content),
                                HeaderInfo.CreateSingle<long> ("Content-Length", Parser.Long.TryParse, HttpHeaderKind.Content),
                                HeaderInfo.CreateSingle<Uri> ("Content-Location", Parser.Uri.TryParse, HttpHeaderKind.Content),
                                HeaderInfo.CreateSingle<byte[]> ("Content-MD5", Parser.MD5.TryParse, HttpHeaderKind.Content),
@@ -117,19 +117,19 @@ namespace System.Net.Http.Headers
                                HeaderInfo.CreateSingle<DateTimeOffset> ("Last-Modified", Parser.DateTime.TryParse, HttpHeaderKind.Content),
                                HeaderInfo.CreateSingle<Uri> ("Location", Parser.Uri.TryParse, HttpHeaderKind.Response),
                                HeaderInfo.CreateSingle<int> ("Max-Forwards", Parser.Int.TryParse, HttpHeaderKind.Request),
-                               HeaderInfo.CreateMultiList<NameValueHeaderValue> ("Pragma", NameValueHeaderValue.TryParsePragma, HttpHeaderKind.Request | HttpHeaderKind.Response),
+                               HeaderInfo.CreateMulti<NameValueHeaderValue> ("Pragma", NameValueHeaderValue.TryParsePragma, HttpHeaderKind.Request | HttpHeaderKind.Response),
                                HeaderInfo.CreateMulti<AuthenticationHeaderValue> ("Proxy-Authenticate", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Response),
                                HeaderInfo.CreateSingle<AuthenticationHeaderValue> ("Proxy-Authorization", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Request),
                                HeaderInfo.CreateSingle<RangeHeaderValue> ("Range", RangeHeaderValue.TryParse, HttpHeaderKind.Request),
                                HeaderInfo.CreateSingle<Uri> ("Referer", Parser.Uri.TryParse, HttpHeaderKind.Request),
                                HeaderInfo.CreateSingle<RetryConditionHeaderValue> ("Retry-After", RetryConditionHeaderValue.TryParse, HttpHeaderKind.Response),
                                HeaderInfo.CreateMulti<ProductInfoHeaderValue> ("Server", ProductInfoHeaderValue.TryParse, HttpHeaderKind.Response),
-                               HeaderInfo.CreateMulti<TransferCodingWithQualityHeaderValue> ("TE", TransferCodingWithQualityHeaderValue.TryParse, HttpHeaderKind.Request),
-                               HeaderInfo.CreateMulti<string> ("Trailer", Parser.Token.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
+                               HeaderInfo.CreateMulti<TransferCodingWithQualityHeaderValue> ("TE", TransferCodingWithQualityHeaderValue.TryParse, HttpHeaderKind.Request, 0),
+                               HeaderInfo.CreateMulti<string> ("Trailer", CollectionParser.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
                                HeaderInfo.CreateMulti<TransferCodingHeaderValue> ("Transfer-Encoding", TransferCodingHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
                                HeaderInfo.CreateMulti<ProductHeaderValue> ("Upgrade", ProductHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
-                               HeaderInfo.CreateMultiList<ProductInfoHeaderValue> ("User-Agent", ProductInfoHeaderValue.TryParse, HttpHeaderKind.Request),
-                               HeaderInfo.CreateMulti<string> ("Vary", Parser.Token.TryParse, HttpHeaderKind.Response),
+                               HeaderInfo.CreateMulti<ProductInfoHeaderValue> ("User-Agent", ProductInfoHeaderValue.TryParse, HttpHeaderKind.Request),
+                               HeaderInfo.CreateMulti<string> ("Vary", CollectionParser.TryParse, HttpHeaderKind.Response),
                                HeaderInfo.CreateMulti<ViaHeaderValue> ("Via", ViaHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
                                HeaderInfo.CreateMulti<WarningHeaderValue> ("Warning", WarningHeaderValue.TryParse, HttpHeaderKind.Request | HttpHeaderKind.Response),
                                HeaderInfo.CreateMulti<AuthenticationHeaderValue> ("WWW-Authenticate", AuthenticationHeaderValue.TryParse, HttpHeaderKind.Response)
index 0f98be658d16be177454f979f3a570f57d3f1978..f87d4f741bfdf951c13e00614d31dda66a320a49 100644 (file)
@@ -46,6 +46,8 @@ namespace System.Net.Http.Headers
                        OpenParens,
                }
 
+               public static readonly Token Empty = new Token (Type.Token, 0, 0);
+
                readonly Type type;
 
                public Token (Type type, int startPosition, int endPosition)
index 5379a6099f19716205de8555eef03b4b1723c293..296010aa2ad5687ccc1487e963398122c412ec58 100644 (file)
@@ -33,7 +33,7 @@ namespace System.Net.Http.Headers
        public class MediaTypeHeaderValue : ICloneable
        {
                internal List<NameValueHeaderValue> parameters;
-               string media_type;
+               internal string media_type;
 
                public MediaTypeHeaderValue (string mediaType)
                {
@@ -150,7 +150,8 @@ namespace System.Net.Http.Headers
 
                        switch (token.Value.Kind) {
                        case Token.Type.SeparatorSemicolon:
-                               if (!NameValueHeaderValue.TryParseParameters (lexer, out parameters))
+                               Token t;
+                               if (!NameValueHeaderValue.TryParseParameters (lexer, out parameters, out t) || t != Token.Type.End)
                                        return false;
                                break;
                        case Token.Type.End:
@@ -167,37 +168,7 @@ namespace System.Net.Http.Headers
                        return true;
                }
 
-               internal static bool TryParse<T> (string input, out T parsedValue, Func<T> factory) where T : MediaTypeHeaderValue
-               {
-                       parsedValue = null;
-
-                       var lexer = new Lexer (input);
-
-                       string media;
-                       List<NameValueHeaderValue> parameters = null;
-                       var token = TryParseMediaType (lexer, out media);
-                       if (token == null)
-                               return false;
-
-                       switch (token.Value.Kind) {
-                       case Token.Type.SeparatorSemicolon:
-                               if (!NameValueHeaderValue.TryParseParameters (lexer, out parameters))
-                                       return false;
-                               break;
-                       case Token.Type.End:
-                               break;
-                       default:
-                               return false;
-                       }
-
-                       parsedValue = factory ();
-                       parsedValue.media_type = media;
-                       parsedValue.parameters = parameters;
-
-                       return true;
-               }
-
-               static Token? TryParseMediaType (Lexer lexer, out string media)
+               internal static Token? TryParseMediaType (Lexer lexer, out string media)
                {
                        media = null;
 
index a3415fc1e1aaa42a4e9437f14f44338b5cba493b..1cf406dbfdc05efae168d768d44455884cb2a93c 100644 (file)
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Collections.Generic;
+
 namespace System.Net.Http.Headers
 {
        public sealed class MediaTypeWithQualityHeaderValue : MediaTypeHeaderValue
@@ -65,7 +67,40 @@ namespace System.Net.Http.Headers
 
                public static bool TryParse (string input, out MediaTypeWithQualityHeaderValue parsedValue)
                {
-                       return TryParse (input, out parsedValue, () => new MediaTypeWithQualityHeaderValue ());
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
+                       parsedValue = null;
+                       return false;
+               }
+
+               static bool TryParseElement (Lexer lexer, out MediaTypeWithQualityHeaderValue parsedValue, out Token t)
+               {
+                       parsedValue = null;
+
+                       string media;
+                       List<NameValueHeaderValue> parameters = null;
+                       var token = TryParseMediaType (lexer, out media);
+                       if (token == null) {
+                               t = Token.Empty;
+                               return false;
+                       }
+
+                       t = token.Value;
+                       if (t == Token.Type.SeparatorSemicolon && (!NameValueHeaderValue.TryParseParameters (lexer, out parameters, out t) || t != Token.Type.End))
+                               return false;
+
+                       parsedValue = new MediaTypeWithQualityHeaderValue ();
+                       parsedValue.media_type = media;
+                       parsedValue.parameters = parameters;
+                       return true;
+               }
+
+               internal static bool TryParse (string input, int minimalCount, out List<MediaTypeWithQualityHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
                }
        }
 }
index 906ab3aa657fac2845c31f92c377980b68d8299c..e3766a4eb154b6e6e3e3a900985f50974ccded22 100644 (file)
@@ -32,7 +32,7 @@ namespace System.Net.Http.Headers
 {
        public class NameValueHeaderValue : ICloneable
        {
-               string value;
+               internal string value;
 
                public NameValueHeaderValue (string name)
                        : this (name, null)
@@ -53,11 +53,11 @@ namespace System.Net.Http.Headers
                        this.value = source.value;
                }
 
-               private NameValueHeaderValue ()
+               internal NameValueHeaderValue ()
                {
                }
 
-               public string Name { get; private set; }
+               public string Name { get; internal set; }
 
                public string Value {
                        get {
@@ -121,27 +121,22 @@ namespace System.Net.Http.Headers
                        throw new FormatException (input);
                }
 
-               internal static bool TryParseParameters (Lexer lexer, out List<NameValueHeaderValue> result)
+               internal static bool TryParsePragma (string input, int minimalCount, out List<NameValueHeaderValue> result)
                {
-                       return TryParseCollection (lexer, out result, Token.Type.SeparatorSemicolon);
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
                }
 
-               internal static bool TryParsePragma (string input, out List<NameValueHeaderValue> result)
-               {                       
-                       return TryParseCollection (new Lexer (input), out result, Token.Type.SeparatorComma);
-               }
-
-               static bool TryParseCollection (Lexer lexer, out List<NameValueHeaderValue> result, Token.Type separator)
+               internal static bool TryParseParameters (Lexer lexer, out List<NameValueHeaderValue> result, out Token t)
                {               
                        var list = new List<NameValueHeaderValue> ();
                        result = null;
 
-                       Token t;
-
-                       do {
+                       while (true) {
                                var attr = lexer.Scan ();
-                               if (attr != Token.Type.Token)
+                               if (attr != Token.Type.Token) {
+                                       t = Token.Empty;
                                        return false;
+                               }
 
                                string value = null;
 
@@ -156,19 +151,17 @@ namespace System.Net.Http.Headers
                                        t = lexer.Scan ();
                                }
 
-                               if (t == separator|| t == Token.Type.End) {
-                                       list.Add (new NameValueHeaderValue () {
-                                               Name = lexer.GetStringValue (attr),
-                                               value = value
-                                       });
-                               } else {
-                                       return false;
-                               }
+                               list.Add (new NameValueHeaderValue () {
+                                       Name = lexer.GetStringValue (attr),
+                                       value = value
+                               });
 
-                       } while (t == separator);
+                               if (t == Token.Type.SeparatorSemicolon)
+                                       continue;
 
-                       result = list;
-                       return true;
+                               result = list;
+                               return true;
+                       }
                }
 
                public override string ToString ()
@@ -181,35 +174,39 @@ namespace System.Net.Http.Headers
 
                public static bool TryParse (string input, out NameValueHeaderValue parsedValue)
                {
-                       parsedValue = null;
-
                        var lexer = new Lexer (input);
-                       var t = lexer.Scan ();
-                       if (t != Token.Type.Token && t != Token.Type.QuotedString)
-                               return false;
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
 
-                       string v = null;
-                       var token2 = lexer.Scan ();
-                       if (token2 != Token.Type.End) {
-                               if (token2 != Token.Type.SeparatorEqual)
-                                       return false;
-
-                               token2 = lexer.Scan ();
+                       parsedValue = null;
+                       return false;
+               }
 
-                               if (token2 == Token.Type.Token || token2 == Token.Type.QuotedString) {
-                                       v = lexer.GetStringValue (token2);
-                                       token2 = lexer.Scan ();
-                               }
+               static bool TryParseElement (Lexer lexer, out NameValueHeaderValue parsedValue, out Token t)
+               {
+                       parsedValue = null;
 
-                               if (token2 != Token.Type.End)
-                                       return false;
-                       }
+                       t = lexer.Scan ();
+                       if (t != Token.Type.Token)
+                               return false;
 
                        parsedValue = new NameValueHeaderValue () {
                                Name = lexer.GetStringValue (t),
-                               value = v
                        };
 
+                       t = lexer.Scan ();
+                       if (t == Token.Type.SeparatorEqual) {
+                               t = lexer.Scan ();
+
+                               if (t == Token.Type.Token || t == Token.Type.QuotedString) {
+                                       parsedValue.value = lexer.GetStringValue (t);
+                                       t = lexer.Scan ();
+                               } else {
+                                       return false;
+                               }
+                       }
+
                        return true;
                }
        }
index 81d7bb089c1317259d51a4bec1992d405a776e0d..3d328341845b0c96f805bea2eff1da724fa2858b 100644 (file)
@@ -53,8 +53,8 @@ namespace System.Net.Http.Headers
                        }
                }
 
-               private NameValueWithParametersHeaderValue (NameValueHeaderValue source)
-                       : base (source)
+               private NameValueWithParametersHeaderValue ()
+                       : base ()
                {
                }
 
@@ -102,15 +102,52 @@ namespace System.Net.Http.Headers
 
                public static bool TryParse (string input, out NameValueWithParametersHeaderValue parsedValue)
                {
-                       List<NameValueHeaderValue> values;
-                       if (!TryParseParameters (new Lexer (input), out values)) {
-                               parsedValue = null;
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
+                       parsedValue = null;
+                       return false;
+               }
+
+               internal static bool TryParse (string input, int minimalCount, out List<NameValueWithParametersHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
+
+               static bool TryParseElement (Lexer lexer, out NameValueWithParametersHeaderValue parsedValue, out Token t)
+               {
+                       parsedValue = null;
+
+                       t = lexer.Scan ();
+                       if (t != Token.Type.Token)
                                return false;
+
+                       parsedValue = new NameValueWithParametersHeaderValue () {
+                               Name = lexer.GetStringValue (t),
+                       };
+
+                       t = lexer.Scan ();
+                       if (t == Token.Type.SeparatorEqual) {
+                               t = lexer.Scan ();
+
+                               if (t == Token.Type.Token || t == Token.Type.QuotedString) {
+                                       parsedValue.value = lexer.GetStringValue (t);
+                                       t = lexer.Scan ();
+                               } else {
+                                       return false;
+                               }
+                       }
+
+                       if (t == Token.Type.SeparatorSemicolon) {
+                               List<NameValueHeaderValue> result;
+                               if (!TryParseParameters (lexer,  out result, out t))
+                                       return false;
+
+                               parsedValue.parameters = result;
                        }
 
-                       parsedValue = new NameValueWithParametersHeaderValue (values[0]);
-                       values.RemoveAt (0);
-                       parsedValue.parameters = values;
                        return true;
                }
        }
index a6d80d7375bd243df2677742d25ef36e9c5bf7fa..79a3ca380c8400c671c795a802635587dcceabe8 100644 (file)
@@ -28,6 +28,7 @@
 
 using System.Net.Mail;
 using System.Globalization;
+using System.Collections.Generic;
 
 namespace System.Net.Http.Headers
 {
index 306c9f228c8679346692e5272c9a141e64de58bd..9614df12939009d8f476dbca0c6f8a8a1ec1b5fe 100644 (file)
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Collections.Generic;
+
 namespace System.Net.Http.Headers
 {
        public class ProductHeaderValue : ICloneable
@@ -87,15 +89,30 @@ namespace System.Net.Http.Headers
 
                public static bool TryParse (string input, out ProductHeaderValue parsedValue)
                {
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
                        parsedValue = null;
+                       return false;
+               }
 
-                       var lexer = new Lexer (input);
-                       var t = lexer.Scan ();
+               internal static bool TryParse (string input, int minimalCount, out List<ProductHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
+
+               static bool TryParseElement (Lexer lexer, out ProductHeaderValue parsedValue, out Token t)
+               {
+                       parsedValue = null;
+
+                       t = lexer.Scan ();
                        if (t != Token.Type.Token)
                                return false;
 
-                       var value = new ProductHeaderValue ();
-                       value.Name = lexer.GetStringValue (t);
+                       parsedValue = new ProductHeaderValue ();
+                       parsedValue.Name = lexer.GetStringValue (t);
 
                        t = lexer.Scan ();
                        if (t == Token.Type.SeparatorSlash) {
@@ -103,14 +120,10 @@ namespace System.Net.Http.Headers
                                if (t != Token.Type.Token)
                                        return false;
 
-                               value.Version = lexer.GetStringValue (t);
+                               parsedValue.Version = lexer.GetStringValue (t);
                                t = lexer.Scan ();
                        }
 
-                       if (t != Token.Type.End)
-                               return false;
-
-                       parsedValue = value;
                        return true;
                }
 
index daf47ac31e89148e21898397a7abb86d59321929..baace53ed8e9c1d8098ab24653473c5fdf2eda1f 100644 (file)
@@ -106,7 +106,7 @@ namespace System.Net.Http.Headers
                        return true;
                }
 
-               internal static bool TryParse (string input, out List<ProductInfoHeaderValue> result)
+               internal static bool TryParse (string input, int minimalCount, out List<ProductInfoHeaderValue> result)
                {
                        var list = new List<ProductInfoHeaderValue> ();
                        var lexer = new Lexer (input);
@@ -118,8 +118,12 @@ namespace System.Net.Http.Headers
                                        return false;
 
                                if (element == null) {
-                                       result = list;
-                                       return true;
+                                       if (list != null && minimalCount <= list.Count) {
+                                               result = list;
+                                               return true;
+                                       }
+
+                                       return false;
                                }
 
                                list.Add (element);
index 635ed00223c52e18962a8e9666735ef6955199ef..648d4222e36486b7eb366d210dea5f649cbc6f4a 100644 (file)
@@ -27,6 +27,8 @@
 //
 
 using System.Globalization;
+using System.Collections.Generic;
+
 namespace System.Net.Http.Headers
 {
        public class StringWithQualityHeaderValue : ICloneable
@@ -82,10 +84,24 @@ namespace System.Net.Http.Headers
                
                public static bool TryParse (string input, out StringWithQualityHeaderValue parsedValue)
                {
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
                        parsedValue = null;
+                       return false;
+               }
 
-                       var lexer = new Lexer (input);
-                       var t = lexer.Scan ();
+               internal static bool TryParse (string input, int minimalCount, out List<StringWithQualityHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
+
+               static bool TryParseElement (Lexer lexer, out StringWithQualityHeaderValue parsedValue, out Token t)
+               {
+                       parsedValue = null;
+                       t = lexer.Scan ();
                        if (t != Token.Type.Token)
                                return false;
 
@@ -120,9 +136,6 @@ namespace System.Net.Http.Headers
                                t = lexer.Scan ();
                        }
 
-                       if (t != Token.Type.End)
-                               return false;
-
                        parsedValue = value;
                        return true;
                }
index 8f0db592831379f6c38f4bfe07d0f75dec0e8576..6e9825ea4cebd5d8aaf70709d8931aa2af70e9bd 100644 (file)
@@ -32,7 +32,7 @@ namespace System.Net.Http.Headers
 {
        public class TransferCodingHeaderValue : ICloneable
        {
-               string value;
+               internal string value;
                internal List<NameValueHeaderValue> parameters;
 
                public TransferCodingHeaderValue (string value)
@@ -106,30 +106,36 @@ namespace System.Net.Http.Headers
 
                public static bool TryParse (string input, out TransferCodingHeaderValue parsedValue)
                {
-                       return TryParse (input, out parsedValue, () => new TransferCodingHeaderValue ());
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
+                       parsedValue = null;
+                       return false;
                }
 
-               internal static bool TryParse<T> (string input, out T parsedValue, Func<T> factory) where T : TransferCodingHeaderValue
+               internal static bool TryParse (string input, int minimalCount, out List<TransferCodingHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }       
+
+               static bool TryParseElement (Lexer lexer, out TransferCodingHeaderValue parsedValue, out Token t)
                {
                        parsedValue = null;
 
-                       var lexer = new Lexer (input);
-                       var t = lexer.Scan ();
+                       t = lexer.Scan ();
                        if (t != Token.Type.Token)
                                return false;
 
-                       var result = factory ();
+                       var result = new TransferCodingHeaderValue ();
                        result.value = lexer.GetStringValue (t);
 
                        t = lexer.Scan ();
 
                        // Parameters parsing
-                       if (t == Token.Type.SeparatorSemicolon) {
-                               if (!NameValueHeaderValue.TryParseParameters (lexer, out result.parameters))
-                                       return false;
-                       } else if (t != Token.Type.End) {
+                       if (t == Token.Type.SeparatorSemicolon && (!NameValueHeaderValue.TryParseParameters (lexer, out result.parameters, out t) || t != Token.Type.End))
                                return false;
-                       }
 
                        parsedValue = result;
                        return true;
index 0a6e08373c6f07bb66a15038d30d0c3426df10b7..845b95ef5cba47f4ff0c40f8c2adc5e3e2f4f959 100644 (file)
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Collections.Generic;
+
 namespace System.Net.Http.Headers
 {
        public sealed class TransferCodingWithQualityHeaderValue : TransferCodingHeaderValue
@@ -65,7 +67,39 @@ namespace System.Net.Http.Headers
 
                public static bool TryParse (string input, out TransferCodingWithQualityHeaderValue parsedValue)
                {
-                       return TryParse (input, out parsedValue, () => new TransferCodingWithQualityHeaderValue ());
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
+                       parsedValue = null;
+                       return false;
+               }
+
+               internal static bool TryParse (string input, int minimalCount, out List<TransferCodingWithQualityHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
+
+               static bool TryParseElement (Lexer lexer, out TransferCodingWithQualityHeaderValue parsedValue, out Token t)
+               {
+                       parsedValue = null;
+
+                       t = lexer.Scan ();
+                       if (t != Token.Type.Token)
+                               return false;
+
+                       var result = new TransferCodingWithQualityHeaderValue ();
+                       result.value = lexer.GetStringValue (t);
+
+                       t = lexer.Scan ();
+
+                       // Parameters parsing
+                       if (t == Token.Type.SeparatorSemicolon && (!NameValueHeaderValue.TryParseParameters (lexer, out result.parameters, out t) || t != Token.Type.End))
+                               return false;
+
+                       parsedValue = result;
+                       return true;
                }
        }
 }
index 4da14004e13189d47bd2bf89c2a927d35167c7d2..9381977ee17d1a351c95765636604230cee9240c 100644 (file)
@@ -26,6 +26,8 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Collections.Generic;
+
 namespace System.Net.Http.Headers
 {
        public class ViaHeaderValue : ICloneable
@@ -110,11 +112,25 @@ namespace System.Net.Http.Headers
                
                public static bool TryParse (string input, out ViaHeaderValue parsedValue)
                {
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
                        parsedValue = null;
+                       return false;
+               }
 
-                       var lexer = new Lexer (input);
+               internal static bool TryParse (string input, int minimalCount, out List<ViaHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
 
-                       var t = lexer.Scan ();
+               static bool TryParseElement (Lexer lexer, out ViaHeaderValue parsedValue, out Token t)  
+               {
+                       parsedValue = null;
+
+                       t = lexer.Scan ();
                        if (t != Token.Type.Token)
                                return false;
 
@@ -150,8 +166,9 @@ namespace System.Net.Http.Headers
                        value.ReceivedBy = lexer.GetStringValue (next, t);
 
                        string comment;
-                       if (!lexer.ScanCommentOptional (out comment))
-                               return false;
+                       if (lexer.ScanCommentOptional (out comment, out t)) {
+                               t = lexer.Scan ();
+                       }
 
                        value.Comment = comment;
                        parsedValue = value;
index fc58299cf0bd0d25dff4223992a0a7adb45faa06..5c65339ef7af02940d04391260eca6c4fd5f096b 100644 (file)
@@ -27,6 +27,7 @@
 //
 
 using System.Globalization;
+using System.Collections.Generic;
 
 namespace System.Net.Http.Headers
 {
@@ -100,13 +101,28 @@ namespace System.Net.Http.Headers
 
                        throw new FormatException (input);
                }
-               
+
                public static bool TryParse (string input, out WarningHeaderValue parsedValue)
                {
+                       var lexer = new Lexer (input);
+                       Token token;
+                       if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
+                               return true;
+
                        parsedValue = null;
+                       return false;
+               }
 
-                       var lexer = new Lexer (input);
-                       var t = lexer.Scan ();
+               internal static bool TryParse (string input, int minimalCount, out List<WarningHeaderValue> result)
+               {
+                       return CollectionParser.TryParse (input, minimalCount, TryParseElement, out result);
+               }
+
+               static bool TryParseElement (Lexer lexer, out WarningHeaderValue parsedValue, out Token t)      
+               {
+                       parsedValue = null;
+
+                       t = lexer.Scan ();
 
                        if (t != Token.Type.Token)
                                return false;
@@ -148,9 +164,6 @@ namespace System.Net.Http.Headers
                                t = lexer.Scan ();
                        }
 
-                       if (t != Token.Type.End)
-                               return false;
-
                        parsedValue = value;
                        return true;
                }
index ccca104fd9da0b80011f95b3e36e0b335cc25b3e..b40b2a170c175e0c8ad47addaa7bbc68333ab706 100644 (file)
@@ -22,6 +22,7 @@ System.Net.Http/StringContent.cs
 System.Net.Http.Headers/AuthenticationHeaderValue.cs
 System.Net.Http.Headers/CacheControlHeaderValue.cs
 System.Net.Http.Headers/CollectionExtensions.cs
+System.Net.Http.Headers/CollectionParser.cs
 System.Net.Http.Headers/ContentDispositionHeaderValue.cs
 System.Net.Http.Headers/ContentRangeHeaderValue.cs
 System.Net.Http.Headers/EntityTagHeaderValue.cs
index 7d08832868a21d7979e0b44317863340c796fcf4..32cf785a0e9d5ffbdfd042d99926c6edea25c7f9 100644 (file)
@@ -157,6 +157,9 @@ namespace MonoTests.System.Net.Http.Headers
                        NameValueHeaderValue res;
                        Assert.IsFalse (NameValueHeaderValue.TryParse ("", out res), "#1");
                        Assert.IsNull (res, "#2");
+
+                       Assert.IsFalse (NameValueHeaderValue.TryParse ("\"a\"=b", out res), "#3");
+                       Assert.IsNull (res, "#4");
                }
        }
 }
index b852fdc05fdc9d1476ef6a9f14827fb21afe7801..79ae114f65b661d703abb11f32e58a59d2215f00 100644 (file)
@@ -35,6 +35,7 @@ using System.Net.Http;
 using System.Net;
 using System.Net.Http.Headers;
 using System.Linq;
+using System.IO;
 
 namespace MonoTests.System.Net.Http
 {
@@ -361,15 +362,55 @@ namespace MonoTests.System.Net.Http
                }
 
                [Test]
-               public void Headers_Complex ()
+               public void Headers_MultiValues ()
                {
                        HttpRequestMessage message = new HttpRequestMessage ();
                        HttpRequestHeaders headers = message.Headers;
 
+                       headers.Add ("Accept", "application/vnd.citrix.requesttokenresponse+xml, application/vnd.citrix.requesttokenchoices+xml");
+                       headers.Add ("Accept-Charset", "aa ;Q=0,bb;Q=1");
+                       headers.Add ("Expect", "x=1; v, y=5");
+                       headers.Add ("If-Match", "\"a\",*, \"b\",*");
                        headers.Add ("user-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36");
 
+                       Assert.AreEqual (2, headers.Accept.Count, "#1a");
+                       Assert.IsTrue (headers.Accept.SequenceEqual (
+                               new[] {
+                                       new MediaTypeWithQualityHeaderValue ("application/vnd.citrix.requesttokenresponse+xml"),
+                                       new MediaTypeWithQualityHeaderValue ("application/vnd.citrix.requesttokenchoices+xml"),
+                               }
+                       ), "#1b");
 
-                       Assert.AreEqual (6, headers.UserAgent.Count);
+                       Assert.AreEqual (2, headers.AcceptCharset.Count, "#2a");
+                       Assert.IsTrue (headers.AcceptCharset.SequenceEqual (
+                               new[] {
+                                       new StringWithQualityHeaderValue ("aa", 0),
+                                       new StringWithQualityHeaderValue ("bb", 1),
+                               }
+                       ), "#2b");
+
+                       Assert.AreEqual (2, headers.Expect.Count, "#3a");
+                       var expect_expected = new[] {
+                                       new NameValueWithParametersHeaderValue ("x", "1") {
+                                       },
+                                       new NameValueWithParametersHeaderValue ("y", "5"),
+                               };
+                       expect_expected [0].Parameters.Add (new NameValueHeaderValue ("v"));
+                       Assert.IsTrue (headers.Expect.SequenceEqual (
+                               expect_expected
+                       ), "#3b");
+
+                       Assert.AreEqual (4, headers.IfMatch.Count, "#4a");
+                       Assert.IsTrue (headers.IfMatch.SequenceEqual (
+                               new[] {
+                                       new EntityTagHeaderValue ("\"a\""),
+                                       EntityTagHeaderValue.Any,
+                                       new EntityTagHeaderValue ("\"b\""),
+                                       EntityTagHeaderValue.Any
+                               }
+                       ), "#4b");
+
+                       Assert.AreEqual (6, headers.UserAgent.Count, "#10a");
 
                        Assert.IsTrue (headers.UserAgent.SequenceEqual (
                                new[] {
@@ -380,7 +421,7 @@ namespace MonoTests.System.Net.Http
                                        new ProductInfoHeaderValue ("Chrome", "29.0.1547.62"),
                                        new ProductInfoHeaderValue ("Safari", "537.36")
                                }
-                       ));                     
+                       ), "#10b");
                }
 
                [Test]
index b92b3e644d6f304732d29f807ce1bc95e45797a2..b13e8cae417b606b62d8428c031f39966c4faf1f 100644 (file)
@@ -294,6 +294,56 @@ namespace MonoTests.System.Net.Http
                        Assert.AreEqual (3, i, "#10");
                }
 
+               [Test]
+               public void Headers_MultiValues ()
+               {
+                       var message = new HttpResponseMessage ();
+                       var headers = message.Headers;
+
+                       headers.Add ("Proxy-Authenticate", "x, y, z,i");
+                       headers.Add ("Upgrade", "HTTP/2.0, SHTTP/1.3, IRC, RTA/x11");
+                       headers.Add ("Via", "1.0 fred, 1.1 nowhere.com (Apache/1.1)");
+                       headers.Add ("Warning", "199 Miscellaneous \"w\", 200 a \"b\"");
+
+                       Assert.AreEqual (4, headers.ProxyAuthenticate.Count, "#1a");
+                       Assert.IsTrue (headers.ProxyAuthenticate.SequenceEqual (
+                               new[] {
+                                       new AuthenticationHeaderValue ("x"),
+
+                                       new AuthenticationHeaderValue ("y"),
+                                       new AuthenticationHeaderValue ("z"),
+                                       new AuthenticationHeaderValue ("i")
+                               }
+                       ), "#1b");
+
+                       
+                       Assert.AreEqual (4, headers.Upgrade.Count, "#2a");
+                       Assert.IsTrue (headers.Upgrade.SequenceEqual (
+                               new[] {
+                                       new ProductHeaderValue ("HTTP", "2.0"),
+                                       new ProductHeaderValue ("SHTTP", "1.3"),
+                                       new ProductHeaderValue ("IRC"),
+                                       new ProductHeaderValue ("RTA", "x11")
+                               }
+                       ), "#2b");
+
+                       Assert.AreEqual (2, headers.Via.Count, "#3a");
+                       Assert.IsTrue (headers.Via.SequenceEqual (
+                               new[] {
+                                       new ViaHeaderValue ("1.0", "fred"),
+                                       new ViaHeaderValue ("1.1", "nowhere.com", null, "(Apache/1.1)")
+                               }
+                       ), "#2b");
+
+                       Assert.AreEqual (2, headers.Warning.Count, "#4a");
+                       Assert.IsTrue (headers.Warning.SequenceEqual (
+                               new[] {
+                                       new WarningHeaderValue (199, "Miscellaneous", "\"w\""),
+                                       new WarningHeaderValue (200, "a", "\"b\"")
+                               }
+                       ), "#4b");
+               }
+
                [Test]
                public void Header_BaseImplementation ()
                {
index edd4b839c164c1e7d638067ac367a3dfa2dc3ecf..413e459526e155331dd378ae912f78f61e99554e 100644 (file)
@@ -308,6 +308,21 @@ namespace MonoTests.System.Net.Http
                        }
                }
 
+               [Test]
+               public void Headers_Multi ()
+               {
+                       var sc = new StreamContent (MemoryStream.Null);
+                       var headers = sc.Headers;
+
+                       headers.Add ("Allow", "");
+                       headers.Add ("Allow", "a , b, c");
+
+                       Assert.AreEqual (3, headers.Allow.Count, "#1a");
+                       Assert.IsTrue (headers.Allow.SequenceEqual (
+                               new[] { "a", "b", "c" }
+                       ), "#1b");
+               }
+
                [Test]
                public void LoadIntoBuffer ()
                {
index ccca104fd9da0b80011f95b3e36e0b335cc25b3e..b40b2a170c175e0c8ad47addaa7bbc68333ab706 100644 (file)
@@ -22,6 +22,7 @@ System.Net.Http/StringContent.cs
 System.Net.Http.Headers/AuthenticationHeaderValue.cs
 System.Net.Http.Headers/CacheControlHeaderValue.cs
 System.Net.Http.Headers/CollectionExtensions.cs
+System.Net.Http.Headers/CollectionParser.cs
 System.Net.Http.Headers/ContentDispositionHeaderValue.cs
 System.Net.Http.Headers/ContentRangeHeaderValue.cs
 System.Net.Http.Headers/EntityTagHeaderValue.cs
index d56ecc9c089141149ac55cb6fb607415eb0020ef..3f74f8bf98e316f19c0048f08abfc8329dc0d882 100644 (file)
@@ -35,7 +35,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args $(RESX_RESOURCES:.resources=.resx) $(PREBUILT)
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.Core.dll
 NO_SIGN_ASSEMBLY = yes
index 8c6dee9af40207a26fe02edc69c121ed6d1292b0..c603f89a68a1e6a9b4d22b32d54e0f59ab4184c7 100644 (file)
@@ -24,7 +24,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.Debugger.dll
 NO_SIGN_ASSEMBLY = yes
index e7b128f3813acfa295c09e97bdde638075c55f04..234a63b12d968e644acbd323c88e5ca078b93f17 100644 (file)
@@ -24,7 +24,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.Experimental.dll
 NO_SIGN_ASSEMBLY = yes
index 967a34327dedc252bce24e7128581e54bc2fbb1c..acee40d296023127ef0df4d15a28239e729fe6fe 100644 (file)
@@ -21,7 +21,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.Interfaces.dll
 NO_SIGN_ASSEMBLY = yes
index 3afa5560431d689a6389bafd2c99f783b123ce06..18a3360dafe6dec51060f10bb31126f2243af418 100644 (file)
@@ -36,7 +36,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args $(RESX_RESOURCES:.resources=.resx) $(PREBUILT)
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.Linq.dll
 NO_SIGN_ASSEMBLY = yes
index 23a462f80a16eb1e4aa2476c215cf86905c72697..6a35d936f6b33d0254536ec93fb281e3b30e6fda 100644 (file)
@@ -35,7 +35,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args $(RESX_RESOURCES:.resources=.resx) $(PREBUILT)
 
-VALID_PROFILE := $(filter monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.Observable.Aliases.dll
 NO_SIGN_ASSEMBLY = yes
index 80e88566ca6d2b1006b7e4a20d63e4097ccff13a..187dd7702ff703129bde87582049c7256087c4be 100644 (file)
@@ -42,7 +42,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -r:Mono.Reactive.Tests.dll
 
 EXTRA_DISTFILES = more_build_args $(RESX_RESOURCES:.resources=.resx) $(PREBUILT)
 
-VALID_PROFILE := $(filter monotouch monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monotouch monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.PlatformServices.dll
 NO_SIGN_ASSEMBLY = yes
index 06ec402a0df5d5c058ce2fedfeb1b411c0bc9ace..bb695d90ee2092544e3879b2b6a813950281a5d2 100644 (file)
@@ -37,7 +37,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
 
 EXTRA_DISTFILES = more_build_args $(RESX_RESOURCES:.resources=.resx) $(PREBUILT)
 
-VALID_PROFILE := $(filter monodroid net_4_0 net_4_5, $(PROFILE))
+VALID_PROFILE := $(filter monodroid xammac net_4_0 net_4_5, $(PROFILE))
 ifndef VALID_PROFILE
 LIBRARY_NAME = dummy-System.System.Reactive.Providers.dll
 NO_SIGN_ASSEMBLY = yes
diff --git a/mcs/class/System.Runtime.Serialization/xammac_System.Runtime.Serialization.dll.sources b/mcs/class/System.Runtime.Serialization/xammac_System.Runtime.Serialization.dll.sources
new file mode 100644 (file)
index 0000000..6caafd4
--- /dev/null
@@ -0,0 +1 @@
+#include mobile_System.Runtime.Serialization.dll.sources
index 5d255ac84461544d7d886c76adc9a670146b7922..87bd458413b2699626454a24ac6dca4419e77963 100644 (file)
@@ -92,10 +92,8 @@ namespace System.ServiceModel.Dispatcher
                                else if (parameter [0] != '"')
                                        return parameter;
                                break;
-#if !NET_2_1
                        case TypeCode.Char:
                                return parameter != null ? Char.Parse (parameter): default (char);
-#endif
                        case TypeCode.SByte:
                                return parameter != null ? SByte.Parse (parameter, CultureInfo.InvariantCulture): default (sbyte);
                        case TypeCode.Byte:
index 09752f05134ab68f26e966402393fee06621724d..bb25332df4411a2e7fcf5195414c112cbd39a26d 100644 (file)
@@ -74,10 +74,8 @@ namespace System.ServiceModel.Dispatcher
                        switch (Type.GetTypeCode (parameterType)) {
                        case TypeCode.String:
                                return parameter;
-#if !NET_2_1
                        case TypeCode.Char:
                                return parameter != null ? Char.Parse (parameter) : default (char);
-#endif
                        case TypeCode.SByte:
                                return parameter != null ? SByte.Parse (parameter, CultureInfo.InvariantCulture): default (sbyte);
                        case TypeCode.Byte:
index b3154c34b76b553763ede143db12740296b7ba29..f26113c51bb29f97b247afb0ac99c314c041dd91 100644 (file)
@@ -36,6 +36,7 @@ namespace System.ServiceModel.Web
        {
                internal OutgoingWebRequestContext ()
                {
+                       Headers = new WebHeaderCollection ();
                }
 
                public string Accept { get; set; }
index 96beea59c41f22ef54726ab2cbd7cf49ed1aa5ab..32d9e3606bf5cb2d38f680c8cb45833cdf258a2b 100644 (file)
@@ -38,12 +38,7 @@ using System.ServiceModel.Configuration;
 
 namespace System.ServiceModel
 {
-       public class WebHttpBinding
-#if NET_2_1
-        : Binding
-#else
-        : Binding, IBindingRuntimePreferences
-#endif
+       public class WebHttpBinding : Binding, IBindingRuntimePreferences
        {
                public WebHttpBinding ()
                        : this (String.Empty)
@@ -211,11 +206,9 @@ namespace System.ServiceModel
                        return new BindingElementCollection (new BindingElement [] { msgenc, t.Clone () });
                }
 
-#if !NET_2_1
                bool IBindingRuntimePreferences.ReceiveSynchronously {
                        get { return receive_synchronously; }
                }
-#endif
 
 #if NET_4_0
                [EditorBrowsable (EditorBrowsableState.Advanced)]
index f8ca883f83275ec1f704e2e3992c03801148b59e..875acb2117ec61a67808e9e4c99958795ec84a7f 100644 (file)
@@ -33,10 +33,6 @@ using System.Collections.Specialized;
 using System.Globalization;
 using System.Text;
 
-#if NET_2_1
-using NameValueCollection = System.Object;
-#endif
-
 namespace System
 {
        public class UriTemplate
@@ -174,11 +170,8 @@ namespace System
                        foreach (string name in names) {
                                int s = template.IndexOf ('{', src);
                                int e = template.IndexOf ('}', s + 1);
-#if NET_2_1
-                               string value = null;
-#else
                                string value = nvc != null ? nvc [name] : null;
-#endif
+
                                if (dic != null)
                                        dic.TryGetValue (name, out value);
 
index fca94d761cad0701f02b9f952947ef486cbefedd..b437f43d5d2b7e5c22a5c5ff20c3b152562bfa5e 100644 (file)
@@ -29,10 +29,6 @@ using System;
 using System.Collections.ObjectModel;
 using System.Collections.Specialized;
 
-#if NET_2_1
-using NameValueCollection = System.Collections.Generic.Dictionary<string,string>;
-#endif
-
 namespace System
 {
        public class UriTemplateMatch
index d1e8ea5ff58df3d3a1a3336a09c14a23bd31475a..a87a5fd32a495e6562f49e659b9e349b64dc7d56 100644 (file)
@@ -45,7 +45,10 @@ namespace MonoTests.System.ServiceModel.Web
        [TestFixture]
        public class WebOperationContextTest
        {
+// MonoTouch does not support dynamic proxy code generation.
+#if !MONOTOUCH
                [Test]
+#endif
                public void Current ()
                {
 #if !MOBILE
@@ -61,6 +64,9 @@ namespace MonoTests.System.ServiceModel.Web
                                Assert.IsNotNull (WebOperationContext.Current.IncomingRequest, "#4");
                                Assert.IsNotNull (WebOperationContext.Current.IncomingResponse, "#5");
                                Assert.IsNotNull (WebOperationContext.Current.OutgoingResponse, "#6"); // pointless though.
+
+                               Assert.IsNotNull (WebOperationContext.Current.OutgoingRequest.Headers, "#7");
+                               Assert.AreEqual (0, WebOperationContext.Current.OutgoingRequest.Headers.Count, "#8");
 #endif
                        }
                        ch.Close ();
diff --git a/mcs/class/System.ServiceModel.Web/xammac_System.ServiceModel.Web.dll.sources b/mcs/class/System.ServiceModel.Web/xammac_System.ServiceModel.Web.dll.sources
new file mode 100644 (file)
index 0000000..cbea0fa
--- /dev/null
@@ -0,0 +1 @@
+#include mobile_System.ServiceModel.Web.dll.sources
index e209ec8062b37a374ac7b6a661e66d5072a0d2b3..6ebafbd99da921404d65d3adb895336911dfc45b 100644 (file)
@@ -85,7 +85,7 @@ namespace System.ServiceModel.Channels
                                        destination = Via ?? RemoteAddress.Uri;
                        }
 
-                       var web_request = HttpWebRequest.Create (destination);
+                       var web_request = (HttpWebRequest) HttpWebRequest.Create (destination);
                        web_requests.Add (web_request);
                        result.WebRequest = web_request;
                        web_request.Method = "POST";
@@ -145,9 +145,50 @@ namespace System.ServiceModel.Channels
                        string pname = HttpRequestMessageProperty.Name;
                        if (message.Properties.ContainsKey (pname)) {
                                HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname];
-                               foreach (var key in hp.Headers.AllKeys)
-                                       if (!WebHeaderCollection.IsRestricted (key))
+                               foreach (var key in hp.Headers.AllKeys) {
+                                       if (WebHeaderCollection.IsRestricted (key)) { // do not ignore this. WebHeaderCollection rejects restricted ones.
+                                               // FIXME: huh, there should be any better way to do such stupid conversion.
+                                               switch (key) {
+                                               case "Accept":
+                                                       web_request.Accept = hp.Headers [key];
+                                                       break;
+                                               case "Connection":
+                                                       web_request.Connection = hp.Headers [key];
+                                                       break;
+                                               //case "ContentLength":
+                                               //      web_request.ContentLength = hp.Headers [key];
+                                               //      break;
+                                               case "ContentType":
+                                                       web_request.ContentType = hp.Headers [key];
+                                                       break;
+                                               //case "Date":
+                                               //      web_request.Date = hp.Headers [key];
+                                               //      break;
+                                               case "Expect":
+                                                       web_request.Expect = hp.Headers [key];
+                                                       break;
+#if NET_4_0
+                                               case "Host":
+                                                       web_request.Host = hp.Headers [key];
+                                                       break;
+#endif
+                                               //case "If-Modified-Since":
+                                               //      web_request.IfModifiedSince = hp.Headers [key];
+                                               //      break;
+                                               case "Referer":
+                                                       web_request.Referer = hp.Headers [key];
+                                                       break;
+                                               case "Transfer-Encoding":
+                                                       web_request.TransferEncoding = hp.Headers [key];
+                                                       break;
+                                               case "User-Agent":
+                                                       web_request.UserAgent = hp.Headers [key];
+                                                       break;
+                                               }
+                                       }
+                                       else
                                                web_request.Headers [key] = hp.Headers [key];
+                               }
                                web_request.Method = hp.Method;
                                // FIXME: do we have to handle hp.QueryString ?
                                if (hp.SuppressEntityBody)
diff --git a/mcs/class/System.ServiceModel/xammac_System.ServiceModel.dll.sources b/mcs/class/System.ServiceModel/xammac_System.ServiceModel.dll.sources
new file mode 100644 (file)
index 0000000..22ece5c
--- /dev/null
@@ -0,0 +1 @@
+#include mobile_System.ServiceModel.dll.sources
index a89f1d4c83fda4af45556e48f0ba1f1b86412a45..11d78be67c40d35e59541b8cb03254bd18170913 100644 (file)
@@ -2,7 +2,7 @@ thisdir = class/System.Transactions
 SUBDIRS = 
 include ../../build/rules.make
 
-MOBILE_PROFILE := $(filter monotouch monodroid mobile mobile_static, $(PROFILE))
+MOBILE_PROFILE := $(filter monotouch monodroid xammac mobile mobile_static, $(PROFILE))
 
 LIBRARY = System.Transactions.dll
 ifdef MOBILE_PROFILE
index 3cf7228b322edc4f226bf0b06f16dc8b09d5b454..28342175e8a13694789bcf9f19f61c1ea3ae4f46 100644 (file)
@@ -25,6 +25,12 @@ namespace System.Transactions
                public void Done ()
                {
                        done = true;
+
+                       InternalOnDone();
+               }
+
+               internal virtual void InternalOnDone ()
+               {
                }
        }
 }
index 8995fcb851a74f188ecd67b0d03a6915ad8589f0..eaaa277c422aa69f6dc1429c5a940067a22c885c 100644 (file)
@@ -35,6 +35,11 @@ namespace System.Transactions
                        ForceRollback (null);
                }
 
+               internal override void InternalOnDone ()
+               {
+                       this.Prepared();                        
+               }
+
                [MonoTODO]
                public void ForceRollback (Exception ex)
                {
index 9a4d1cfed1fb46646aabccb6626032881d8d53f6..7b8d5ddacbde59d30e5d2e87dcd085ced65f9665 100644 (file)
@@ -3,7 +3,7 @@ SUBDIRS =
 include ../../build/rules.make
 
 LIBRARY = System.Web.Services.dll
-MOBILE := $(filter monotouch monodroid mobile mobile_static, $(PROFILE))
+MOBILE := $(filter monotouch monodroid xammac mobile mobile_static, $(PROFILE))
 ifdef MOBILE
 LIB_MCS_FLAGS = \
        -nowarn:649 -nowarn:169                 \
diff --git a/mcs/class/System.Web.Services/xammac_System.Web.Services.dll.sources b/mcs/class/System.Web.Services/xammac_System.Web.Services.dll.sources
new file mode 100644 (file)
index 0000000..9e39dcc
--- /dev/null
@@ -0,0 +1 @@
+#include mobile_System.Web.Services.dll.sources
index 9ac8b2cce1885c67bd280bfd93e67ca6e514b200..7c6fa45e89ffeaa399b0de88b88c49ddb1800073 100644 (file)
@@ -193,7 +193,7 @@ namespace System.Web.Security
                                if (returnValue == 0)
                                        return true;
                                if (returnValue == 1)
-                                       return false; //role does not exists
+                                       return false; //role does not exist
                                else if (returnValue == 2 && throwOnPopulatedRole)
                                        throw new ProviderException (rolename + " is not empty");
                                else
index 0a8268a632c011c5dceb20ec9000657119e7b75c..8d7a9a9afa614d7a58c2772f2f3bc3e00904979e 100644 (file)
@@ -138,7 +138,7 @@ namespace MonoTests.System.Xml
                        nr.Read ();     // root\r
                        nr.Read ();     // &ent3;\r
                        Assert.AreEqual (XmlNodeType.EntityReference, nr.NodeType);\r
-                       // ent3 does not exists in this dtd.\r
+                       // ent3 does not exist in this dtd.\r
                        nr.ResolveEntity ();\r
                        Assert.AreEqual (XmlNodeType.EntityReference, nr.NodeType);\r
                        nr.Read ();\r
@@ -170,7 +170,7 @@ namespace MonoTests.System.Xml
                        nr.Read ();     // root\r
                        nr.Read ();     // &ent;\r
                        Assert.AreEqual (XmlNodeType.EntityReference, nr.NodeType);\r
-                       // ent does not exists in this dtd.\r
+                       // ent does not exist in this dtd.\r
                        nr.ResolveEntity ();\r
                }\r
 \r
index 21006f72963a4b7a5707f6eff8f9c4f2999186f2..7ecd83780aec5a8121073bdaeeec49166d670a8a 100644 (file)
@@ -1074,7 +1074,7 @@ namespace MonoTests.System.Xml
                        dvr.Read ();    // root
                        dvr.Read ();    // &ent3;
                        Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType);
-                       // ent3 does not exists in this dtd.
+                       // ent3 does not exist in this dtd.
                        Assert.AreEqual (XmlNodeType.EntityReference, dvr.NodeType);
                        try {
                                dvr.ResolveEntity ();
index 2b538893e7a0b32fda3f675d3fcc79aa60670fe6..c3a961794bf82e5c66cd2f8141e3a40affea9eb5 100644 (file)
@@ -608,7 +608,7 @@ namespace nist_dom.fundamental
         //--------------------------- test case core-0011M ---------------------------\r
         //\r
         // Testing feature - The "removeNamedItem(name)" method returns null if the\r
-        //                   name specified does not exists in the map.\r
+        //                   name specified does not exist in the map.\r
         //\r
         // Testing approach - Retrieve the third employee and create a NamedNodeMap\r
         //                    object from the attributes in its last child.\r
diff --git a/mcs/class/System.XML/xammac_System.Xml.dll.sources b/mcs/class/System.XML/xammac_System.Xml.dll.sources
new file mode 100644 (file)
index 0000000..b663093
--- /dev/null
@@ -0,0 +1 @@
+#include mobile_System.Xml.dll.sources
index f2caec0386d3c3e7ccb38bfa87b8ba27efca2c5d..e428def11c26b54d53e6423d659e7a10fdf607fe 100755 (executable)
@@ -541,6 +541,21 @@ in network-byte-order.</para>
         <remarks>To be added.</remarks>
       </Docs>
     </Member>
+    <Member MemberName="IsIPv6Teredo">
+      <MemberSignature Language="C#" Value="public bool IsIPv6Teredo { get; }" />
+      <MemberType>Property</MemberType>
+      <AssemblyInfo>
+        <AssemblyVersion>4.0.0.0</AssemblyVersion>
+      </AssemblyInfo>
+      <ReturnValue>
+        <ReturnType>System.Boolean</ReturnType>
+      </ReturnValue>
+      <Docs>
+        <summary>To be added.</summary>
+        <value>To be added.</value>
+        <remarks>To be added.</remarks>
+      </Docs>
+    </Member>
     <Member MemberName="IsLoopback">
       <MemberSignature Language="ILASM" Value=".method public hidebysig static bool IsLoopback(class System.Net.IPAddress address)" />
       <MemberSignature Language="C#" Value="public static bool IsLoopback (System.Net.IPAddress addr);" />
index 3b25daa8977eecc2a4328aae9fd5dff0971002d1..dd2008edc0f53492f20f349d5aee04b380bb4903 100644 (file)
@@ -26,8 +26,8 @@ TEST_MCS_FLAGS = -r:System.Drawing.dll -r:Mono.Security.dll -r:System.Data -r:Sy
 ifneq (1, $(FRAMEWORK_VERSION_MAJOR))
 LIB_MCS_FLAGS = -nowarn:618 -d:CONFIGURATION_2_0 -unsafe $(RESOURCE_FILES:%=-resource:%)
 TEST_MCS_FLAGS += -r:System.Configuration
-PROFILE_ANY_MOBILE := $(filter monotouch monodroid, $(PROFILE))
-NOT_SL := $(filter net_2_0 net_4_0 net_4_5 monotouch_runtime monodroid mobile, $(PROFILE))
+PROFILE_ANY_MOBILE := $(filter monotouch monodroid xammac, $(PROFILE))
+NOT_SL := $(filter net_2_0 net_4_0 net_4_5 monotouch_runtime monodroid mobile xammac, $(PROFILE))
 endif
 ifeq (2.1, $(FRAMEWORK_VERSION))
 LIB_MCS_FLAGS += -d:INSIDE_SYSTEM
index 4f95b0c54c87b8db0fe3833e37f3a05c532dd525..de67153fc0cf587e71eaf50995941dafa3eb7481 100644 (file)
@@ -188,18 +188,7 @@ namespace System.Collections.Generic
                
                public bool Contains (T value)
                {
-                       LinkedListNode <T> node = first;
-                       if (node == null)
-                               return false;
-                       do
-                       {
-                               if (value.Equals (node.Value))
-                                       return true;
-                               node = node.forward;
-                       }
-                       while (node != first);
-
-                       return false;
+                       return Find (value) != null;
                }
                
                public void CopyTo (T [] array, int index)
@@ -225,35 +214,44 @@ namespace System.Collections.Generic
                        while (node != first);
                }
                
-               public LinkedListNode <T> Find (T value)
+               public LinkedListNode<T> Find (T value)
                {
-                       LinkedListNode <T> node = first;
+                       var node = first;
                        if (node == null)
                                return null;
-                       do
-                       {
-                               if ( (value == null && node.Value == null) || 
-                                    (value != null && value.Equals (node.Value)) )
-                                       return node;
+
+                       do {
+                               if (value == null) {
+                                       if (node.Value == null)
+                                               return node;
+                               } else {
+                                       if (EqualityComparer<T>.Default.Equals (node.Value, value))
+                                               return node;
+                               }
+
                                node = node.forward;
-                       }
-                       while (node != first);
+                       } while (node != first);
 
                        return null;
                }
                
-               public LinkedListNode <T> FindLast (T value)
+               public LinkedListNode<T> FindLast (T value)
                {
-                       LinkedListNode <T> node = first;
+                       var node = first;
                        if (node == null)
                                return null;
-                       do
-                       {
+
+                       do {
                                node = node.back;
-                               if (value.Equals (node.Value))
-                                       return node;
-                       }
-                       while (node != first);
+
+                               if (value == null) {
+                                       if (node.Value == null)
+                                               return node;
+                               } else {
+                                       if (EqualityComparer<T>.Default.Equals (node.Value, value))
+                                               return node;
+                               }
+                       } while (node != first);
 
                        return null;
                }
index b64d655efe0fa0b941f2209a056d12609699ecae..b4c0ce8b69b1cb2ba325bf0bd81adaa229b173eb 100644 (file)
@@ -242,7 +242,7 @@ namespace System.ComponentModel {
                        if (raise_list_changed_events)
                                OnListChanged (new ListChangedEventArgs (ListChangedType.ItemAdded, index));
 
-                       if (type_raises_item_changed_events)
+                       if (item != null && type_raises_item_changed_events)
                                (item as INotifyPropertyChanged).PropertyChanged += Item_PropertyChanged;
                }
 
index d92f827f7fa4f48c00f68b61edb65c65b6a3992e..125f07805f9403f212fe5789357ff92bd0d02f33 100644 (file)
@@ -93,7 +93,7 @@ namespace System.IO {
                                throw new ArgumentException ("Empty path", "path");
 
                        if (!Directory.Exists (path))
-                               throw new ArgumentException ("Directory does not exists", "path");
+                               throw new ArgumentException ("Directory does not exist", "path");
 
                        this.enableRaisingEvents = false;
                        this.filter = filter;
@@ -312,7 +312,7 @@ namespace System.IO {
                                        throw new ArgumentException ("Invalid directory name", "value", exc);
 
                                if (!exists)
-                                       throw new ArgumentException ("Directory does not exists", "value");
+                                       throw new ArgumentException ("Directory does not exist", "value");
 
                                path = value;
                                fullpath = null;
index de9754e951d0a812c3128a35c4cdcf5789991184..91b0e8afca99c054b100cc41e6583d0f2269fdd3 100644 (file)
@@ -107,7 +107,7 @@ namespace System.Net.NetworkInformation {
                        try {
                                networkChange = new MacNetworkChange ();
                        } catch {
-#if !NETWORK_CHANGE_STANDALONE
+#if !NETWORK_CHANGE_STANDALONE && !MONOTOUCH
                                networkChange = new LinuxNetworkChange ();
 #endif
                        }
@@ -318,7 +318,7 @@ namespace System.Net.NetworkInformation {
                }
        }
 
-#if !NETWORK_CHANGE_STANDALONE
+#if !NETWORK_CHANGE_STANDALONE && !MONOTOUCH
 
        internal sealed class LinuxNetworkChange : INetworkChange {
                [Flags]
index 2dd7d1ab31166198b8a2518a90c5bad0ff084a2c..b1081f5bd29cfd9e05496bdff1c9b150729a7801 100644 (file)
@@ -333,6 +333,16 @@ namespace System.Net {
                        }
                }
 
+#if NET_4_0
+               public bool IsIPv6Teredo {
+                       get {
+                               return m_Family != AddressFamily.InterNetwork &&
+                                       m_Numbers[0] == 0x2001 &&
+                                       m_Numbers[1] == 0;
+                       }
+               }
+#endif
+
                public long ScopeId {
                        get {
                                if (m_Family != AddressFamily.InterNetworkV6)
index f5605744bdde26c024ed28a84b58607a79ecccfd..ad898b102dd71e53a308a3837791eb20b73e8229 100644 (file)
@@ -12,6 +12,24 @@ namespace MonoTests.System.Collections.Generic
        [TestFixture]
        public class LinkedListTest
        {
+               class EquatableValue : IEquatable<EquatableValue>
+               {
+                       public readonly string Value;
+
+                       public EquatableValue (string value)
+                       {
+                               this.Value = value;
+                       }
+
+                       public bool Equals (EquatableValue other)
+                       {
+                               if (other == null)
+                                       return false;
+
+                               return string.Equals (Value, other.Value, StringComparison.OrdinalIgnoreCase);
+                       }
+               }
+
                LinkedList <int> intlist;
                LinkedList <string> strings;
 
@@ -280,6 +298,19 @@ namespace MonoTests.System.Collections.Generic
                        Assert.AreEqual ("efgh", li.Last.Value);
                        Assert.AreEqual ("abcd", li.First.Value);
                }
+
+               [Test]
+               public void EqualityComparer ()
+               {
+                       var list = new LinkedList<EquatableValue> ();
+                       var mv  = new EquatableValue ("first");
+                       list.AddFirst (mv);
+
+                       var test = new EquatableValue ("FIRST");
+                       Assert.IsTrue (list.Contains (test), "#1");
+                       Assert.AreSame (mv, list.Find (test).Value, "#2");
+                       Assert.AreSame (mv, list.FindLast (test).Value, "#3");
+               }
        }
 }
 
index 88be568f429b51540cf9967c8e84e15cc1864c36..92a6253db915b6bc3d0d3643689b8ae02f134512 100644 (file)
@@ -629,6 +629,16 @@ namespace MonoTests.System.ComponentModel
                        Assert.IsTrue (added, "ItemAdded");
                        Assert.IsTrue (changed, "ItemChanged");
                }
+               
+               [Test] // https://bugzilla.xamarin.com/show_bug.cgi?id=16902
+               public void Bug16902 ()
+               {
+                       var list = new BindingList<Item> ();
+                       list.Insert (0, null);
+                       var count = list.Count;
+                       
+                       Assert.AreEqual (1, count, "1");
+               }
        }
 }
 
index 965b1cd44a0c2eed655483df96addd70c932922b..505bdfb881c0efdb2efc36942a15ac6311d02ebc 100644 (file)
@@ -545,6 +545,15 @@ public class IPAddressTest
                Assert.IsTrue (IPAddress.Parse ("FF01::1").IsIPv6Multicast, "#2");
                Assert.IsFalse (IPAddress.Parse ("FE00::1").IsIPv6Multicast, "#3");
        }
+
+#if NET_4_0
+       [Test]
+       public void IsIPv6Teredo ()
+       {
+               Assert.IsFalse (IPAddress.Parse ("2001::1").IsIPv6Teredo, "#1");
+               Assert.IsFalse (IPAddress.Parse ("2002::1").IsIPv6Teredo, "#2");
+       }
+#endif
 }
 }
 
index f5ffb4ac713333aa3eb1654448b09b41162448f2..d5e815bedac344d8c9a057ccfd28f576f9036f5e 100644 (file)
@@ -1,6 +1,7 @@
 Assembly/AssemblyInfo.cs
 Mono.Http/NtlmClient.cs
 System.CodeDom.Compiler/GeneratedCodeAttribute.cs
+System.CodeDom.Compiler/IndentedTextWriter.cs
 System.Collections.Generic/ISet.cs
 System.Collections.Generic/LinkedList.cs
 System.Collections.Generic/LinkedListNode.cs
index 019f8681bd186d69f849f06af8941bfd50f989af..af382cd209be213569fa918d7af0421909169402 100644 (file)
@@ -1,3 +1,2 @@
 #include mobile_System.dll.sources
 System/AndroidPlatform.cs
-System.CodeDom.Compiler/IndentedTextWriter.cs
diff --git a/mcs/class/System/xammac_System.dll.sources b/mcs/class/System/xammac_System.dll.sources
new file mode 100644 (file)
index 0000000..70a77a6
--- /dev/null
@@ -0,0 +1 @@
+#include mobile_System.dll.sources
index d48bb2685654783ca8ddaf2cde72d7bbdcb6a25b..d7b92b38541e42a0d7888c6f06acf15fb94c85f1 100644 (file)
@@ -517,11 +517,11 @@ namespace System.IO {
                        do {
                                int readLen = Math.Min (MaxBufferSize, len);
                                
-                               int n = m_stream.Read (charByteBuffer, 0, readLen);
-                               if (n == 0)
+                               readLen = m_stream.Read (charByteBuffer, 0, readLen);
+                               if (readLen == 0)
                                        throw new EndOfStreamException();
                                
-                               int cch = decoder.GetChars (charByteBuffer, 0, n, charBuffer, 0);
+                               int cch = decoder.GetChars (charByteBuffer, 0, readLen, charBuffer, 0);
 
                                if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
                                        return new String (charBuffer, 0, cch);
index 6066c031cba72eb04542b7c30d45fd55193eb802..baa366a7efbc309f2c5f4b345cec3aa567b1efe8 100644 (file)
@@ -140,7 +140,7 @@ namespace System.IO
                        if (!success) {
                                /*
                                 * FIXME:
-                                * In io-layer/io.c rmdir returns error_file_not_found if directory does not exists.
+                                * In io-layer/io.c rmdir returns error_file_not_found if directory does not exist.
                                 * So maybe this could be handled somewhere else?
                                 */
                                if (error == MonoIOError.ERROR_FILE_NOT_FOUND) {
index d718e1fb05b2d9c634958aba436b9102271b7729..17119e612bea968cb5881223f93d3386f3bd22f2 100644 (file)
@@ -153,7 +153,7 @@ namespace System.IO
                {
                        byte[] buffer = new byte [1];
 
-                       if (Read (buffer, 0, 1) == 1)
+                       if (Read (buffer, 0, 1) > 0)
                                return buffer [0];
                        
                        return -1;
index e53cdbb097eef5c5e85d80ca73b9c5fe73042a7b..c73c6ada22b50f7009f5b9cabfbab4b7c4feea89 100644 (file)
@@ -570,7 +570,7 @@ namespace System.Reflection.Emit
                        if (resourceFileName.Length == 0)
                                throw new ArgumentException ("resourceFileName");
                        if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
-                               throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
+                               throw new FileNotFoundException ("File '" + resourceFileName + "' does not exist or is a directory.");
                        if (native_resource != NativeResourceType.None)
                                throw new ArgumentException ("Native resource has already been defined.");
 
index 1aceb94ef07fb636b397d88853fcd8c23a1316f4..55cc465e04421bd331aa9fc5d4369478a097fd60 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit
index 0a7a464b7689b621308c54d3e7af15eaadf3aab6..8a852c139420c3622ba6fac9f39eaf1e6d6d1463 100644 (file)
@@ -25,7 +25,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index 94d35f80f51808459d13eda5261c5367b0f4c0a5..427b93d98dbb2fe9b63cfc439e1df18e5b749a18 100644 (file)
@@ -30,7 +30,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index 2ccff2a919bf83e184df1bdb0476d7cf456a5128..119a871441155f3534a494b28e2e90f89c58de7c 100644 (file)
@@ -25,7 +25,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index eab1cd0b8c9432cd6b7aa3d0191b03c36760429c..32aa0b81fbe407e3c628485bfef489947820f426 100644 (file)
@@ -1,4 +1,3 @@
-
 //
 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
 //
@@ -534,7 +533,7 @@ namespace System.Reflection.Emit {
                        if (resourceFileName == String.Empty)
                                throw new ArgumentException ("resourceFileName");
                        if (!File.Exists (resourceFileName) || Directory.Exists (resourceFileName))
-                               throw new FileNotFoundException ("File '" + resourceFileName + "' does not exists or is a directory.");
+                               throw new FileNotFoundException ("File '" + resourceFileName + "' does not exist or is a directory.");
 
                        throw new NotImplementedException ();
                }
index 81edbd5b5ad44382a6662842d83f6e813940a794..e6cdf10b73785b36f1489c055c1de78dbf98cab8 100644 (file)
 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
 //
 
-#if !FULL_AOT_RUNTIME
-using System;
-using System.Reflection;
-using System.Reflection.Emit;
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
+
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index bcac4a31c1d4421dd23724a8dd74e3604236c4e9..1163869317e9ab7c8d7c75055c6b8dd4a655e18e 100644 (file)
@@ -1,4 +1,4 @@
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 namespace System.Reflection.Emit {
        static class OpCodeNames {
                internal static readonly string [] names = {
index 681ea6e4ff58da99ad03856642bc6f4bc2d6de80..df0cbf0d50a659499d30f18e21268913b6ad4597 100644 (file)
@@ -25,7 +25,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index 840ee183ffcba131c010ab00eda22b672c6631a2..6e891d538d45ed3dfc59083402a6d1074f450df2 100644 (file)
@@ -1,4 +1,4 @@
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index c8f785d0d3d84d3341a7519d9936430d28916cc5..2985b1b57ee0b5679081e19791641a0e738a8e79 100644 (file)
@@ -25,7 +25,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index 4cf610fab3561f9e72eb1abcae318b25832aac9f..adb9998e66ef4a999312c29926c33e762c4b8e3c 100644 (file)
@@ -22,7 +22,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index 689197c919cba83dcb55d5a2a50417a6e5cc7112..16a271495926aa4e1fd61c990b76076dc7b89328 100644 (file)
@@ -25,7 +25,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !FULL_AOT_RUNTIME
+#if !FULL_AOT_RUNTIME || IOS_REFLECTION
 using System.Runtime.InteropServices;
 
 namespace System.Reflection.Emit {
index 796b863336e3084b18782fbeecc5b840d0420a09..8d75e83951681a17270a77139a161ed1f349233a 100644 (file)
@@ -351,8 +351,7 @@ namespace System.Threading.Tasks
                        continuations.Add (continuation);
                        
                        // Retry in case completion was achieved but event adding was too late
-                       if (IsCompleted) {
-                               continuations.Remove (continuation);
+                       if (IsCompleted && continuations.Remove (continuation)) {
                                if (!canExecuteInline)
                                        return false;
 
index e5906be5a5bffddbc4e6e8c4ee79477bfc50a444..12eaa8be194323b611aa6ad6bcd42f3a5593d67c 100644 (file)
@@ -339,6 +339,7 @@ namespace System.Threading.Tasks
        sealed class CountdownContinuation : IContinuation, IDisposable
        {
                readonly CountdownEvent evt;
+               bool disposed;
 
                public CountdownContinuation (int initialCount)
                {
@@ -353,12 +354,18 @@ namespace System.Threading.Tasks
 
                public void Dispose ()
                {
+                       disposed = true;
+                       Thread.MemoryBarrier ();
+       
                        evt.Dispose ();
                }
 
                public void Execute ()
                {
-                       evt.Signal ();
+                       // Guard against possible race when continuation is disposed and some tasks may still
+                       // execute it (removal was late and the execution is slower than the Dispose thread)
+                       if (!disposed)
+                               evt.Signal ();
                }
        }
 
index 59637dd0a35e212c5685648d6c1c78d8501bc5ed..c5557f0446e69b7808e73a295b08c7c244d4e469 100644 (file)
@@ -61,7 +61,7 @@ namespace System.Threading
 #if NET_4_5
                        timer_callback = token => {
                                var cts = (CancellationTokenSource) token;
-                               cts.Cancel ();
+                               cts.CancelSafe ();
                        };
 #endif
                }
@@ -118,23 +118,46 @@ namespace System.Threading
                public void Cancel (bool throwOnFirstException)
                {
                        CheckDisposed ();
+                       Cancellation (throwOnFirstException);
+               }
+
+               //
+               // Don't throw ObjectDisposedException if the callback
+               // is called concurrently with a Dispose
+               //
+               public void CancelSafe ()
+               {
+                       if (!disposed)
+                               Cancellation (true);
+               }
 
+               void Cancellation (bool throwOnFirstException)
+               {
                        if (canceled)
                                return;
 
                        Thread.MemoryBarrier ();
                        canceled = true;
-                       
-                       handle.Set ();
+
+                       Thread.MemoryBarrier ();
+
+                       // Dispose might be running at same time
+                       if (!disposed)
+                               handle.Set ();
+
                        if (linkedTokens != null)
                                UnregisterLinkedTokens ();
-                       
+
+                       var cbs = callbacks;
+                       if (cbs == null)
+                               return;
+
                        List<Exception> exceptions = null;
-                       
+
                        try {
                                Action cb;
                                for (int id = currId; id != int.MinValue; id--) {
-                                       if (!callbacks.TryRemove (new CancellationTokenRegistration (id, this), out cb))
+                                       if (!cbs.TryRemove (new CancellationTokenRegistration (id, this), out cb))
                                                continue;
                                        if (cb == null)
                                                continue;
@@ -153,24 +176,13 @@ namespace System.Threading
                                        }
                                }
                        } finally {
-                               callbacks.Clear ();
+                               cbs.Clear ();
                        }
 
                        if (exceptions != null)
                                throw new AggregateException (exceptions);
                }
 
-               /* This is the callback registered on linked tokens
-                * so that they don't throw an ODE if the callback
-                * is called concurrently with a Dispose
-                */
-               void SafeLinkedCancel ()
-               {
-                       try {
-                               Cancel ();
-                       } catch (ObjectDisposedException) {}
-               }
-
 #if NET_4_5
                public void CancelAfter (TimeSpan delay)
                {
@@ -212,7 +224,7 @@ namespace System.Threading
                                throw new ArgumentException ("Empty tokens array");
 
                        CancellationTokenSource src = new CancellationTokenSource ();
-                       Action action = src.SafeLinkedCancel;
+                       Action action = src.CancelSafe;
                        var registrations = new List<CancellationTokenRegistration> (tokens.Length);
 
                        foreach (CancellationToken token in tokens) {
@@ -250,18 +262,20 @@ namespace System.Threading
                void Dispose (bool disposing)
                {
                        if (disposing && !disposed) {
-                               Thread.MemoryBarrier ();
                                disposed = true;
+                               Thread.MemoryBarrier ();
 
                                if (!canceled) {
-                                       Thread.MemoryBarrier ();
                                        UnregisterLinkedTokens ();
                                        callbacks = null;
+                               } else {
+                                       handle.WaitOne ();
                                }
 #if NET_4_5
                                if (timer != null)
                                        timer.Dispose ();
 #endif
+
                                handle.Dispose ();
                        }
                }
index 5d8be432ca403593d1455cc4379fe3da4e63a601..852d69089b3dcbf72739707831f01b8c46903a91 100644 (file)
@@ -1459,6 +1459,88 @@ namespace MonoTests.System.IO
                }
        }
 
+       class ReadStringMockStream : Stream
+       {
+               int noc;
+
+               #region implemented abstract members of Stream
+
+               public override void Flush ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override int Read (byte[] buffer, int offset, int count)
+               {
+                       switch (noc++) {
+                       case 0:
+                               buffer [0] = 42; // Length
+                               return 2; 
+                       default:
+                               buffer [0] = 0x65;
+                               return 1;
+                       }
+               }
+
+               public override long Seek (long offset, SeekOrigin origin)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override void SetLength (long value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override void Write (byte[] buffer, int offset, int count)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override bool CanRead {
+                       get {
+                               return true;
+                       }
+               }
+
+               public override bool CanSeek {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+               }
+
+               public override bool CanWrite {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+               }
+
+               public override long Length {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+               }
+
+               public override long Position {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+                       set {
+                               throw new NotImplementedException ();
+                       }
+               }
+
+               #endregion
+       }
+
+       [Test]
+       public void ReadSting_CustomStream ()
+       {
+               var sr = new BinaryReader (new ReadStringMockStream ());
+               var s = sr.ReadString ();
+               Assert.AreEqual ("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", s);
+       }
+
        [Test]
        public void ReadOverrides ()
        {
index 6267439aed26efa4406e56557551b5a9a4bd3df5..112978ae8b7684f5e1af71eff32e3063a4b6ad17 100644 (file)
@@ -2760,5 +2760,53 @@ namespace MonoTests.System.IO
                        }
                }
 #endif
+
+               void MoveTest (FileAccess acc, FileShare share, bool works)
+               {
+                       var file = "kk597rfdnllh89";
+
+                       File.Delete (file + ".old");
+                       using (var v = File.Create (file)) { }
+
+                       using (var stream = new FileStream(file, FileMode.Open, acc, share, 4096, FileOptions.SequentialScan)) {
+                               try {
+                                       File.Move(file, file + ".old");
+                                       if (!works)
+                                               Assert.Fail ("Move with ({0}) and  ({1}) did not fail", acc, share);
+                               } catch (IOException) {
+                                       if (works)
+                                               Assert.Fail ("Move with ({0}) and  ({1}) did fail", acc, share);
+                               }
+                       }
+               }
+
+               [Test]
+               public void MoveTest ()
+               {
+                       MoveTest (FileAccess.Read, FileShare.None, false);
+                       MoveTest (FileAccess.Read, FileShare.Read, false);
+                       MoveTest (FileAccess.Read, FileShare.Write, false);
+                       MoveTest (FileAccess.Read, FileShare.ReadWrite, false);
+                       MoveTest (FileAccess.Read, FileShare.Delete, true);
+                       MoveTest (FileAccess.Read, FileShare.Read | FileShare.Delete, true);
+                       MoveTest (FileAccess.Read, FileShare.Write | FileShare.Delete, true);
+                       MoveTest (FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, true);
+                       MoveTest (FileAccess.Write, FileShare.None, false);
+                       MoveTest (FileAccess.Write, FileShare.Read, false);
+                       MoveTest (FileAccess.Write, FileShare.Write, false);
+                       MoveTest (FileAccess.Write, FileShare.ReadWrite, false);
+                       MoveTest (FileAccess.Write, FileShare.Delete, true);
+                       MoveTest (FileAccess.Write, FileShare.Read | FileShare.Delete, true);
+                       MoveTest (FileAccess.Write, FileShare.Write | FileShare.Delete, true);
+                       MoveTest (FileAccess.Write, FileShare.ReadWrite | FileShare.Delete, true);
+                       MoveTest (FileAccess.ReadWrite, FileShare.None, false);
+                       MoveTest (FileAccess.ReadWrite, FileShare.Read, false);
+                       MoveTest (FileAccess.ReadWrite, FileShare.Write, false);
+                       MoveTest (FileAccess.ReadWrite, FileShare.ReadWrite, false);
+                       MoveTest (FileAccess.ReadWrite, FileShare.Delete, true);
+                       MoveTest (FileAccess.ReadWrite, FileShare.Read | FileShare.Delete, true);
+                       MoveTest (FileAccess.ReadWrite, FileShare.Write | FileShare.Delete, true);
+                       MoveTest (FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, true);
+               }
        }
 }
index 24534c3fd824293fdfee07141233efb38e19ecbe..8aef81c7b1e3e7533833536c520ff85ae90aa691 100644 (file)
@@ -472,6 +472,19 @@ namespace MonoTests.System.Threading
                                t2.Join (500);
                        }, 500);
                }
+
+               [Test]
+               public void DisposeRace ()
+               {
+                       for (int i = 0; i < 1000; ++i) {
+                               var c1 = new CancellationTokenSource ();
+                               using (c1) {
+                                       var wh = c1.Token.WaitHandle;
+                                       c1.CancelAfter (1);
+                                       Thread.Sleep (1);
+                               }
+                       }
+               }
        }
 }
 
index 9c950226391ce42bf60a5e48f7c724be13bab6ba..8772d7afdea04e8771c54266715144cacfffa015 100644 (file)
@@ -3308,6 +3308,14 @@ namespace MonoTests.System
                        TestSerialization (tester, typeof (StuffToPick<int>).GetMethod ("GenericMethod").MakeGenericMethod (typeof (int)));
                }
 
+               [Test]
+               public void ShadowCopyTypeGetTypeMissingAssemblyTest ()
+               {
+                       ad = CreateShadowCopyAppDomain (tempDir, true);
+                       CrossDomainTester tester = CreateCrossDomainTester (ad);
+                       tester.AssertLoadMissingAssemblyType ();
+               }
+
                private static AppDomain CreateTestDomain (string baseDirectory, bool assemblyResolver)
                {
                        AppDomainSetup setup = new AppDomainSetup ();
@@ -3316,6 +3324,15 @@ namespace MonoTests.System
                        return CreateTestDomain (setup, assemblyResolver);
                }
 
+               private static AppDomain CreateShadowCopyAppDomain (string baseDirectory, bool assemblyResolver)
+               {
+                       AppDomainSetup setup = new AppDomainSetup ();
+                       setup.ApplicationBase = baseDirectory;
+                       setup.ApplicationName = "testdomain";
+                       setup.ShadowCopyFiles = "true";
+                       return CreateTestDomain (setup, assemblyResolver);
+               }
+
                private static AppDomain CreateTestDomain (AppDomainSetup setup, bool assemblyResolver)
                {
                        AppDomain ad = AppDomain.CreateDomain ("testdomain",
@@ -3423,22 +3440,17 @@ namespace MonoTests.System
                                }
                        }
 
-                       public bool AssertFileLoadException (AssemblyName assemblyRef)
+                       public void AssertLoadMissingAssemblyType ()
                        {
-                               try {
-                                       AppDomain.CurrentDomain.Load (assemblyRef);
-                                       return false;
-                               } catch (FileLoadException) {
-                                       return true;
-                               }
+                               Assert.IsNull (Type.GetType ("A.B.C, MissingAssembly"));
                        }
 
-                       public bool AssertFileNotFoundException (AssemblyName assemblyRef)
+                       public bool AssertFileLoadException (AssemblyName assemblyRef)
                        {
                                try {
                                        AppDomain.CurrentDomain.Load (assemblyRef);
                                        return false;
-                               } catch (FileNotFoundException) {
+                               } catch (FileLoadException) {
                                        return true;
                                }
                        }
@@ -3608,4 +3620,4 @@ namespace MonoTests.System
        }
 }
 
-#endif
\ No newline at end of file
+#endif
diff --git a/mcs/class/dlr/README b/mcs/class/dlr/README
new file mode 100644 (file)
index 0000000..7ec5bea
--- /dev/null
@@ -0,0 +1,8 @@
+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
new file mode 100644 (file)
index 0000000..880a99a
--- /dev/null
@@ -0,0 +1,5 @@
+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
new file mode 100644 (file)
index 0000000..10f8a96
--- /dev/null
@@ -0,0 +1,133 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..7c75d14
--- /dev/null
@@ -0,0 +1,226 @@
+/* ****************************************************************************
+ *
+ * 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;
+            }
+
+            BigInteger bi = value as BigInteger;
+            if ((object)bi != null) {
+                return BigIntegerConstant(bi);
+#if FEATURE_NUMERICS
+            } else if (value is BigInt) {
+                return BigIntConstant((BigInt)value);
+            } else if (value is Complex) {
+                return ComplexConstant((Complex)value);
+#endif
+            } else if (value is Complex64) {
+                return Complex64Constant((Complex64)value);
+            } else 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);
+            }
+        }
+
+        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
+        }
+
+        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
+
+        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)
+                );
+            }
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Ast/EmptyStatements.cs
new file mode 100644 (file)
index 0000000..0968a2c
--- /dev/null
@@ -0,0 +1,45 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..6b2a08e
--- /dev/null
@@ -0,0 +1,149 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..19477b2
--- /dev/null
@@ -0,0 +1,82 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..165a424
--- /dev/null
@@ -0,0 +1,111 @@
+/* ****************************************************************************
+ *
+ * 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/DebugOptions.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/DebugOptions.cs
new file mode 100644 (file)
index 0000000..a3aac34
--- /dev/null
@@ -0,0 +1,76 @@
+/* ****************************************************************************
+ *
+ * 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.Security;
+using System;
+
+namespace Microsoft.Scripting {
+
+    /// <summary>
+    /// This class holds onto internal debugging options used in this assembly. 
+    /// These options can be set via environment variables DLR_{option-name}.
+    /// Boolean options map "true" to true and other values to false.
+    /// 
+    /// These options are for internal debugging only, and should not be
+    /// exposed through any public APIs.
+    /// </summary>
+    internal static class DebugOptions {
+
+        private static bool ReadOption(string name) {
+#if SILVERLIGHT
+            return false;
+#else
+            string envVar = ReadString(name);
+            return envVar != null && envVar.ToLowerInvariant() == "true";
+#endif
+        }
+
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "name")]
+        private static bool ReadDebugOption(string name) {
+#if DEBUG
+            return ReadOption(name);
+#else
+            return false;
+#endif
+        }
+
+        private static string ReadString(string name) {
+#if FEATURE_PROCESS
+            try {
+                return Environment.GetEnvironmentVariable("DLR_" + name);
+            } catch (SecurityException) {
+                return null;
+            }
+#else
+            return null;
+#endif
+        }
+
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "name")]
+        private static string ReadDebugString(string name) {
+#if DEBUG
+            return ReadString(name);
+#else
+            return null;
+#endif
+        }
+
+        private readonly static bool _trackPerformance = ReadDebugOption("TrackPerformance");
+
+        internal static bool TrackPerformance {
+            get { return _trackPerformance; }
+        }
+    }
+}
\ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/CompilerHelpers.cs
new file mode 100644 (file)
index 0000000..919d1b5
--- /dev/null
@@ -0,0 +1,906 @@
+/* ****************************************************************************
+ *
+ * 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;
+#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 static readonly MethodAttributes PublicStatic = MethodAttributes.Public | MethodAttributes.Static;
+        private static readonly MethodInfo _CreateInstanceMethod = typeof(ScriptingRuntimeHelpers).GetMethod("CreateInstance");
+
+        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 (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)
+                )
+            );
+        }
+
+        #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
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Generation/ConstantCheck.cs
new file mode 100644 (file)
index 0000000..89cbbfe
--- /dev/null
@@ -0,0 +1,128 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..2b5bd93
--- /dev/null
@@ -0,0 +1,110 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..b2ef101
--- /dev/null
@@ -0,0 +1,87 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..de0b6db
--- /dev/null
@@ -0,0 +1,108 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..8535961
--- /dev/null
@@ -0,0 +1,34 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..1f1775c
--- /dev/null
@@ -0,0 +1,243 @@
+/* ****************************************************************************
+ *
+ * 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 : 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 AddInstruction() {
+        }
+
+        internal sealed class AddInt32 : AddInstruction {
+            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(unchecked((Int32)l + (Int32)r));
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddInt16 : AddInstruction {
+            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)unchecked((Int16)l + (Int16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddInt64 : AddInstruction {
+            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)unchecked((Int64)l + (Int64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddUInt16 : AddInstruction {
+            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)unchecked((UInt16)l + (UInt16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddUInt32 : AddInstruction {
+            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)unchecked((UInt32)l + (UInt32)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddUInt64 : AddInstruction {
+            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)unchecked((UInt64)l + (UInt64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddSingle : AddInstruction {
+            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 AddDouble : AddInstruction {
+            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 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 : 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 AddOvfInstruction() {
+        }
+
+        internal sealed class AddOvfInt32 : AddOvfInstruction {
+            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(checked((Int32)l + (Int32)r));
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddOvfInt16 : AddOvfInstruction {
+            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)checked((Int16)l + (Int16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddOvfInt64 : AddOvfInstruction {
+            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)checked((Int64)l + (Int64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddOvfUInt16 : AddOvfInstruction {
+            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)checked((UInt16)l + (UInt16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddOvfUInt32 : AddOvfInstruction {
+            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)checked((UInt32)l + (UInt32)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddOvfUInt64 : AddOvfInstruction {
+            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)checked((UInt64)l + (UInt64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class AddOvfSingle : AddOvfInstruction {
+            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 AddOvfDouble : AddOvfInstruction {
+            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 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
new file mode 100644 (file)
index 0000000..09ec87d
--- /dev/null
@@ -0,0 +1,134 @@
+// 
+// AndbInstruction.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 : Instruction {
+        private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Boolean;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private AndInstruction() {
+        }
+
+        internal sealed class AndInt32 : AndInstruction {
+            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 AndInt16 : AndInstruction {
+            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 AndInt64 : AndInstruction {
+            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 AndUInt16 : AndInstruction {
+            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 AndUInt32 : AndInstruction {
+            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 AndUInt64 : AndInstruction {
+            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 AndBoolean : AndInstruction {
+            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] = (Boolean)((Boolean)l & (Boolean)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 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 override string ToString() {
+            return "And()";
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ArrayOperations.cs
new file mode 100644 (file)
index 0000000..d8e0bc6
--- /dev/null
@@ -0,0 +1,134 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..19163ee
--- /dev/null
@@ -0,0 +1,905 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..fc69ed3
--- /dev/null
@@ -0,0 +1,296 @@
+/* ****************************************************************************
+ *
+ * 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 (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;            
+        }
+
+        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/ControlFlowInstructions.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/ControlFlowInstructions.cs
new file mode 100644 (file)
index 0000000..376488e
--- /dev/null
@@ -0,0 +1,595 @@
+/* ****************************************************************************
+ *
+ * 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 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\92t 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
new file mode 100644 (file)
index 0000000..f7d1497
--- /dev/null
@@ -0,0 +1,132 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..7057669
--- /dev/null
@@ -0,0 +1,76 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..c98b957
--- /dev/null
@@ -0,0 +1,509 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..b2426e7
--- /dev/null
@@ -0,0 +1,55 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..e4edde9
--- /dev/null
@@ -0,0 +1,161 @@
+/* ****************************************************************************
+ *
+ * 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 : Instruction {
+        // Perf: EqualityComparer<T> but is 3/2 to 2 times slower.
+        private static Instruction _Reference, _Boolean, _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private EqualInstruction() {
+        }
+
+        internal sealed class EqualBoolean : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Boolean)frame.Pop()) == ((Boolean)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualSByte : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((SByte)frame.Pop()) == ((SByte)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualInt16 : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Int16)frame.Pop()) == ((Int16)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualChar : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Char)frame.Pop()) == ((Char)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualInt32 : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Int32)frame.Pop()) == ((Int32)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualInt64 : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Int64)frame.Pop()) == ((Int64)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualByte : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Byte)frame.Pop()) == ((Byte)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualUInt16 : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((UInt16)frame.Pop()) == ((UInt16)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualUInt32 : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((UInt32)frame.Pop()) == ((UInt32)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualUInt64 : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((UInt64)frame.Pop()) == ((UInt64)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualSingle : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Single)frame.Pop()) == ((Single)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualDouble : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Double)frame.Pop()) == ((Double)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class EqualReference : EqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(frame.Pop() == frame.Pop());
+                return +1;
+            }
+        }
+
+        [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.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 override string ToString() {
+            return "Equal()";
+        }
+    }
+}
\ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/FieldOperations.cs
new file mode 100644 (file)
index 0000000..4bb8ec6
--- /dev/null
@@ -0,0 +1,94 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..a35f16b
--- /dev/null
@@ -0,0 +1,146 @@
+/* ****************************************************************************
+ *
+ * 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 GreaterThanInstruction : Instruction {
+        private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private GreaterThanInstruction() {
+        }
+
+        internal sealed class GreaterThanSByte : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                SByte right = (SByte)frame.Pop();
+                frame.Push(((SByte)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanInt16 : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Int16 right = (Int16)frame.Pop();
+                frame.Push(((Int16)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanChar : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Char right = (Char)frame.Pop();
+                frame.Push(((Char)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanInt32 : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Int32 right = (Int32)frame.Pop();
+                frame.Push(((Int32)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanInt64 : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Int64 right = (Int64)frame.Pop();
+                frame.Push(((Int64)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanByte : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Byte right = (Byte)frame.Pop();
+                frame.Push(((Byte)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanUInt16 : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                UInt16 right = (UInt16)frame.Pop();
+                frame.Push(((UInt16)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanUInt32 : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                UInt32 right = (UInt32)frame.Pop();
+                frame.Push(((UInt32)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanUInt64 : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                UInt64 right = (UInt64)frame.Pop();
+                frame.Push(((UInt64)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanSingle : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Single right = (Single)frame.Pop();
+                frame.Push(((Single)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        internal sealed class GreaterThanDouble : GreaterThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Double right = (Double)frame.Pop();
+                frame.Push(((Double)frame.Pop()) > right);
+                return +1;
+            }
+        }
+
+        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 override string ToString() {
+            return "GreaterThan()";
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/Instruction.cs
new file mode 100644 (file)
index 0000000..6f67063
--- /dev/null
@@ -0,0 +1,61 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..ca0be09
--- /dev/null
@@ -0,0 +1,115 @@
+/* ****************************************************************************
+ *
+ * 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
+                    { typeof(BigInteger), InstructionFactory<BigInteger>.Factory }  
+                };
+            }
+
+            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);
+    }
+
+    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 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);
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/InstructionList.cs
new file mode 100644 (file)
index 0000000..3fa74e9
--- /dev/null
@@ -0,0 +1,1042 @@
+/* ****************************************************************************
+ *
+ * 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);
+        }
+
+        #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 EmitShl(Type type) {
+            Emit(ShlInstruction.Create(type));
+        }
+
+        public void EmitShr(Type type) {
+            Emit(ShrInstruction.Create(type));
+        }
+
+        public void EmitOr(Type type) {
+            Emit(OrInstruction.Create(type));
+        }
+
+        public void EmitAnd(Type type) {
+            Emit(AndInstruction.Create(type));
+        }
+
+        public void EmitExclusiveOr(Type type) {
+            Emit(XorInstruction.Create(type));
+        }        
+
+        #region Comparisons
+
+        public void EmitEqual(Type type) {
+            Emit(EqualInstruction.Create(type));
+        }
+
+        public void EmitNotEqual(Type type) {
+            Emit(NotEqualInstruction.Create(type));
+        }
+
+        public void EmitLessThan(Type type) {
+            Emit(LessThanInstruction.Create(type));
+        }
+
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
+        public void EmitLessThanOrEqual(Type type) {
+            throw new NotSupportedException();
+        }
+
+        public void EmitGreaterThan(Type type) {
+            Emit(GreaterThanInstruction.Create(type));
+        }
+
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
+        public void EmitGreaterThanOrEqual(Type type) {
+            throw new NotSupportedException();
+        }
+
+        #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) {
+            if (@checked)
+                Emit(NegateOvfInstruction.Create(type));
+            else
+                Emit(NegateInstruction.Create(type));            
+        }
+
+        public void EmitNot(Type type) {
+            Emit(NotInstruction.Create(type));
+        }
+
+        #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 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
new file mode 100644 (file)
index 0000000..2517a85
--- /dev/null
@@ -0,0 +1,309 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..2875e8b
--- /dev/null
@@ -0,0 +1,146 @@
+/* ****************************************************************************
+ *
+ * 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 abstract class LessThanInstruction : Instruction {
+        private static Instruction _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private LessThanInstruction() {
+        }
+
+        internal sealed class LessThanSByte : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                SByte right = (SByte)frame.Pop();
+                frame.Push(((SByte)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanInt16 : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Int16 right = (Int16)frame.Pop();
+                frame.Push(((Int16)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanChar : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Char right = (Char)frame.Pop();
+                frame.Push(((Char)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanInt32 : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Int32 right = (Int32)frame.Pop();
+                frame.Push(((Int32)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanInt64 : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Int64 right = (Int64)frame.Pop();
+                frame.Push(((Int64)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanByte : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Byte right = (Byte)frame.Pop();
+                frame.Push(((Byte)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanUInt16 : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                UInt16 right = (UInt16)frame.Pop();
+                frame.Push(((UInt16)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanUInt32 : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                UInt32 right = (UInt32)frame.Pop();
+                frame.Push(((UInt32)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanUInt64 : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                UInt64 right = (UInt64)frame.Pop();
+                frame.Push(((UInt64)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanSingle : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Single right = (Single)frame.Pop();
+                frame.Push(((Single)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        internal sealed class LessThanDouble : LessThanInstruction {
+            public override int Run(InterpretedFrame frame) {
+                Double right = (Double)frame.Pop();
+                frame.Push(((Double)frame.Pop()) < right);
+                return +1;
+            }
+        }
+
+        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 override string ToString() {
+            return "LessThan()";
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/LocalAccess.cs
new file mode 100644 (file)
index 0000000..bc07095
--- /dev/null
@@ -0,0 +1,374 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..4e8bb37
--- /dev/null
@@ -0,0 +1,145 @@
+// 
+// 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 : 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 ModInstruction() {
+        }
+
+        internal sealed class ModInt32 : ModInstruction {
+            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(unchecked((Int32)l % (Int32)r));
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class ModInt16 : ModInstruction {
+            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)unchecked((Int16)l % (Int16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class ModInt64 : ModInstruction {
+            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)unchecked((Int64)l % (Int64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class ModUInt16 : ModInstruction {
+            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)unchecked((UInt16)l % (UInt16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class ModUInt32 : ModInstruction {
+            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)unchecked((UInt32)l % (UInt32)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class ModUInt64 : ModInstruction {
+            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)unchecked((UInt64)l % (UInt64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class ModSingle : ModInstruction {
+            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 ModDouble : ModInstruction {
+            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 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
new file mode 100644 (file)
index 0000000..4529adc
--- /dev/null
@@ -0,0 +1,256 @@
+// 
+// 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 : 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 MulInstruction() {
+        }
+
+        internal sealed class MulInt32 : MulInstruction {
+            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(unchecked((Int32)l * (Int32)r));
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulInt16 : MulInstruction {
+            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)unchecked((Int16)l * (Int16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulInt64 : MulInstruction {
+            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)unchecked((Int64)l * (Int64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulUInt16 : MulInstruction {
+            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)unchecked((UInt16)l * (UInt16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulUInt32 : MulInstruction {
+            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)unchecked((UInt32)l * (UInt32)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulUInt64 : MulInstruction {
+            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)unchecked((UInt64)l * (UInt64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulSingle : MulInstruction {
+            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 MulDouble : MulInstruction {
+            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 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 : 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 MulOvfInstruction() {
+        }
+
+        internal sealed class MulOvfInt32 : MulOvfInstruction {
+            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(checked((Int32)l * (Int32)r));
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulOvfInt16 : MulOvfInstruction {
+            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)checked((Int16)l * (Int16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulOvfInt64 : MulOvfInstruction {
+            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)checked((Int64)l * (Int64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulOvfUInt16 : MulOvfInstruction {
+            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)checked((UInt16)l * (UInt16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulOvfUInt32 : MulOvfInstruction {
+            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)checked((UInt32)l * (UInt32)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulOvfUInt64 : MulOvfInstruction {
+            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)checked((UInt64)l * (UInt64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class MulOvfSingle : MulOvfInstruction {
+            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 MulOvfDouble : MulOvfInstruction {
+            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 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
new file mode 100644 (file)
index 0000000..58c60f6
--- /dev/null
@@ -0,0 +1,214 @@
+// 
+// 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;
+
+        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) {
+                object 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) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Int16)unchecked(-(Int16)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NegateInt64 : NegateInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Int64)unchecked(-(Int64)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NegateUInt16 : NegateInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (UInt16)unchecked(-(UInt16)v);
+                return 1;
+
+            }
+        }
+
+        internal sealed class NegateUInt32 : NegateInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (UInt32)unchecked(-(UInt32)v);
+                return 1;
+
+            }
+        }
+
+        internal sealed class NegateSingle : NegateInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Single)unchecked(-(Single)v);
+                return 1;
+
+            }
+        }
+
+        internal sealed class NegateDouble : NegateInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Double)unchecked(-(Double)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 override string ToString() {
+            return "Negate()";
+        }
+    }
+
+    internal abstract class NegateOvfInstruction : Instruction {
+        private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _Single, _Double;
+
+        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) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = ScriptingRuntimeHelpers.Int32ToObject(checked(-(Int32)v));
+                return 1;
+            }
+        }
+
+        internal sealed class NegateOvfInt16 : NegateOvfInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Int16)checked(-(Int16)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NegateOvfInt64 : NegateOvfInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Int64)checked(-(Int64)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NegateOvfUInt16 : NegateOvfInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (UInt16)checked(-(UInt16)v);
+                return 1;
+
+            }
+        }
+
+        internal sealed class NegateOvfUInt32 : NegateOvfInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (UInt32)checked(-(UInt32)v);
+                return 1;
+
+            }
+        }
+
+        internal sealed class NegateOvfSingle : NegateOvfInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Single)checked(-(Single)v);
+                return 1;
+
+            }
+        }
+
+        internal sealed class NegateOvfDouble : NegateOvfInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Double)checked(-(Double)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 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
new file mode 100644 (file)
index 0000000..f7da9f4
--- /dev/null
@@ -0,0 +1,162 @@
+/* ****************************************************************************
+ *
+ * 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 : Instruction {
+        // Perf: EqualityComparer<T> but is 3/2 to 2 times slower.
+        private static Instruction _Reference, _Boolean, _SByte, _Int16, _Char, _Int32, _Int64, _Byte, _UInt16, _UInt32, _UInt64, _Single, _Double;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private NotEqualInstruction() {
+        }
+
+        internal sealed class NotEqualBoolean : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Boolean)frame.Pop()) != ((Boolean)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualSByte : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((SByte)frame.Pop()) != ((SByte)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualInt16 : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Int16)frame.Pop()) != ((Int16)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualChar : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Char)frame.Pop()) != ((Char)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualInt32 : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Int32)frame.Pop()) != ((Int32)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualInt64 : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Int64)frame.Pop()) != ((Int64)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualByte : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Byte)frame.Pop()) != ((Byte)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualUInt16 : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((UInt16)frame.Pop()) != ((UInt16)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualUInt32 : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((UInt32)frame.Pop()) != ((UInt32)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualUInt64 : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((UInt64)frame.Pop()) != ((UInt64)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualSingle : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Single)frame.Pop()) != ((Single)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualDouble : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(((Double)frame.Pop()) != ((Double)frame.Pop()));
+                return +1;
+            }
+        }
+
+        internal sealed class NotEqualReference : NotEqualInstruction {
+            public override int Run(InterpretedFrame frame) {
+                frame.Push(frame.Pop() != frame.Pop());
+                return +1;
+            }
+        }
+
+        [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.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 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
new file mode 100644 (file)
index 0000000..3cfce54
--- /dev/null
@@ -0,0 +1,119 @@
+// 
+// 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;
+
+        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) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = ScriptingRuntimeHelpers.Int32ToObject(~(Int32)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NotInt16 : NotInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Int16)(~(Int16)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NotInt64 : NotInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (Int64)(~(Int64)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NotUInt16 : NotInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (UInt64)(~(UInt64)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NotUInt32 : NotInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (UInt32)(~(UInt32)v);
+                return 1;
+            }
+        }
+
+        internal sealed class NotUInt64 : NotInstruction {
+            public override int Run(InterpretedFrame frame) {
+                object v = frame.Data[frame.StackIndex - 1];
+                frame.Data[frame.StackIndex - 1] = (UInt64)(~(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 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
new file mode 100644 (file)
index 0000000..e42515f
--- /dev/null
@@ -0,0 +1,254 @@
+/* ****************************************************************************
+ *
+ * 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;
+                    }
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/OrInstruction.cs
new file mode 100644 (file)
index 0000000..b183b68
--- /dev/null
@@ -0,0 +1,134 @@
+// 
+// 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 : Instruction {
+        private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Boolean;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private OrInstruction() {
+        }
+
+        internal sealed class OrInt32 : OrInstruction {
+            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 OrInt16 : OrInstruction {
+            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 OrInt64 : OrInstruction {
+            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 OrUInt16 : OrInstruction {
+            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 OrUInt32 : OrInstruction {
+            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 OrUInt64 : OrInstruction {
+            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 OrBoolean : OrInstruction {
+            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] = (Boolean)((Boolean)l | (Boolean)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 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 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
new file mode 100644 (file)
index 0000000..4db4553
--- /dev/null
@@ -0,0 +1,123 @@
+// 
+// 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 : Instruction {
+        private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private ShlInstruction() {
+        }
+
+        internal sealed class ShlInt32 : ShlInstruction {
+            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 ShlInt16 : ShlInstruction {
+            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] = (Int32)((Int16)l << (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShlInt64 : ShlInstruction {
+            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 << (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShlUInt16 : ShlInstruction {
+            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] = (Int32)((UInt16)l << (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShlUInt32 : ShlInstruction {
+            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 << (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShlUInt64 : ShlInstruction {
+            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 << (Int32)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 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 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
new file mode 100644 (file)
index 0000000..cefb800
--- /dev/null
@@ -0,0 +1,123 @@
+// 
+// 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 : Instruction {
+        private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private ShrInstruction() {
+        }
+
+        internal sealed class ShrInt32 : ShrInstruction {
+            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 ShrInt16 : ShrInstruction {
+            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] = (Int32)((Int16)l >> (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShrInt64 : ShrInstruction {
+            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 >> (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShrUInt16 : ShrInstruction {
+            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] = (Int32)((UInt16)l >> (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShrUInt32 : ShrInstruction {
+            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 >> (Int32)r);
+                frame.StackIndex--;
+                return 1;
+            }
+        }
+
+        internal sealed class ShrUInt64 : ShrInstruction {
+            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 >> (Int32)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 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 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
new file mode 100644 (file)
index 0000000..e2c9e7d
--- /dev/null
@@ -0,0 +1,117 @@
+/* ****************************************************************************
+ *
+ * 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();
+            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
new file mode 100644 (file)
index 0000000..4571e4f
--- /dev/null
@@ -0,0 +1,256 @@
+// 
+// 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 : 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 SubInstruction() {
+        }
+
+        internal sealed class SubInt32 : SubInstruction {
+            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(unchecked((Int32)l - (Int32)r));
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubInt16 : SubInstruction {
+            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)unchecked((Int16)l - (Int16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubInt64 : SubInstruction {
+            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)unchecked((Int64)l - (Int64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubUInt16 : SubInstruction {
+            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)unchecked((UInt16)l - (UInt16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubUInt32 : SubInstruction {
+            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)unchecked((UInt32)l - (UInt32)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubUInt64 : SubInstruction {
+            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)unchecked((UInt64)l - (UInt64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubSingle : SubInstruction {
+            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 SubDouble : SubInstruction {
+            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 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 : 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 SubOvfInstruction() {
+        }
+
+        internal sealed class SubOvfInt32 : SubOvfInstruction {
+            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(checked((Int32)l - (Int32)r));
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubOvfInt16 : SubOvfInstruction {
+            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)checked((Int16)l - (Int16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubOvfInt64 : SubOvfInstruction {
+            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)checked((Int64)l - (Int64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubOvfUInt16 : SubOvfInstruction {
+            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)checked((UInt16)l - (UInt16)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubOvfUInt32 : SubOvfInstruction {
+            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)checked((UInt32)l - (UInt32)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubOvfUInt64 : SubOvfInstruction {
+            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)checked((UInt64)l - (UInt64)r);
+                frame.StackIndex--;
+                return +1;
+            }
+        }
+
+        internal sealed class SubOvfSingle : SubOvfInstruction {
+            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 SubOvfDouble : SubOvfInstruction {
+            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 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
new file mode 100644 (file)
index 0000000..320deb5
--- /dev/null
@@ -0,0 +1,163 @@
+/* ****************************************************************************
+ *
+ * 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 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()"; }
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/Instructions/XorInstruction.cs
new file mode 100644 (file)
index 0000000..37360a8
--- /dev/null
@@ -0,0 +1,134 @@
+// 
+// AndbInstruction.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 : Instruction {
+        private static Instruction _Int16, _Int32, _Int64, _UInt16, _UInt32, _UInt64, _Boolean;
+
+        public override int ConsumedStack { get { return 2; } }
+        public override int ProducedStack { get { return 1; } }
+
+        private XorInstruction() {
+        }
+
+        internal sealed class XorInt32 : XorInstruction {
+            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 XorInt16 : XorInstruction {
+            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 XorInt64 : XorInstruction {
+            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 XorUInt16 : XorInstruction {
+            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 XorUInt32 : XorInstruction {
+            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 XorUInt64 : XorInstruction {
+            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 XorBoolean : XorInstruction {
+            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] = (Boolean)((Boolean)l ^ (Boolean)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 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 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
new file mode 100644 (file)
index 0000000..cd3a078
--- /dev/null
@@ -0,0 +1,297 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..81c7d5b
--- /dev/null
@@ -0,0 +1,262 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..fa98324
--- /dev/null
@@ -0,0 +1,1700 @@
+/* ****************************************************************************
+ *
+ * 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);
+                        return;
+
+                    case ExpressionType.NotEqual:
+                        CompileNotEqual(node.Left, node.Right);
+                        return;
+
+                    case ExpressionType.LessThan:
+                    case ExpressionType.LessThanOrEqual:
+                    case ExpressionType.GreaterThan:
+                    case ExpressionType.GreaterThanOrEqual:
+                        CompileComparison(node.NodeType, node.Left, node.Right);
+                        return;
+
+                    case ExpressionType.LeftShift:
+                    case ExpressionType.RightShift:
+                        CompileShift(node.NodeType, node.Left, node.Right);
+                        return;
+
+                    case ExpressionType.And:
+                    case ExpressionType.Or:
+                    case ExpressionType.ExclusiveOr:
+                        CompileLogical(node.NodeType, node.Left, node.Right);
+                        return;
+
+                    default:
+                        throw new NotImplementedException(node.NodeType.ToString());
+                }
+            }
+        }
+
+        private void CompileEqual(Expression left, Expression right) {
+            Debug.Assert(left.Type == right.Type || !left.Type.IsValueType() && !right.Type.IsValueType());
+            Compile(left);
+            Compile(right);
+            _instructions.EmitEqual(left.Type);
+        }
+
+        private void CompileNotEqual(Expression left, Expression right) {
+            Debug.Assert(left.Type == right.Type || !left.Type.IsValueType() && !right.Type.IsValueType());
+            Compile(left);
+            Compile(right);
+            _instructions.EmitNotEqual(left.Type);
+        }
+
+        private void CompileComparison(ExpressionType nodeType, Expression left, Expression right) {
+            Debug.Assert(left.Type == right.Type && TypeUtils.IsNumeric(left.Type));
+
+            // TODO:
+            // if (TypeUtils.IsNullableType(left.Type) && liftToNull) ...
+
+            Compile(left);
+            Compile(right);
+            
+            switch (nodeType) {
+                case ExpressionType.LessThan: _instructions.EmitLessThan(left.Type); break;
+                case ExpressionType.LessThanOrEqual: _instructions.EmitLessThanOrEqual(left.Type); break;
+                case ExpressionType.GreaterThan: _instructions.EmitGreaterThan(left.Type); break;
+                case ExpressionType.GreaterThanOrEqual: _instructions.EmitGreaterThanOrEqual(left.Type); 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) {
+            Debug.Assert(right.Type == typeof (int));
+            Compile(left);
+            Compile(right);
+            switch (nodeType) {
+                case ExpressionType.LeftShift: _instructions.EmitShl(left.Type); break;
+                case ExpressionType.RightShift: _instructions.EmitShr(left.Type); break;
+                default: throw Assert.Unreachable;
+            }
+        }
+
+        private void CompileLogical(ExpressionType nodeType, Expression left, Expression right) {
+            Debug.Assert(left.Type == right.Type && TypeUtils.IsIntegerOrBool(left.Type));
+            Compile(left);
+            Compile(right);
+            switch (nodeType) {
+                case ExpressionType.And: _instructions.EmitAnd(left.Type); break;
+                case ExpressionType.Or: _instructions.EmitOr(left.Type); break;
+                case ExpressionType.ExclusiveOr: _instructions.EmitExclusiveOr(left.Type); break;
+                default: throw Assert.Unreachable;
+            }
+        }
+
+        private void CompileConvertUnaryExpression(Expression expr) {
+            var node = (UnaryExpression)expr;
+            if (node.Method != null) {
+                Compile(node.Operand);
+
+                // 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;
+            }
+
+            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) {
+            Compile(node.Operand);
+            _instructions.EmitNegate(node.Type, @checked);
+        }
+
+        private void CompileNotExpression(UnaryExpression node) {
+            Compile(node.Operand);
+            _instructions.EmitNot(node.Type);
+        }
+
+        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);
+                        return;
+                    case ExpressionType.NegateChecked:
+                        CompileNegateExpression(node, true);
+                        return;                    
+                    case ExpressionType.Not:
+                        CompileNotExpression(node);
+                        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.IsPrimitive())) {
+#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 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();
+        }
+
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")]
+        private void CompileQuoteUnaryExpression(Expression expr) {
+            throw new System.NotImplementedException();
+        }
+
+        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);
+
+            // use TypeEqual for sealed types:
+            if (node.TypeOperand.IsSealed()) {
+                _instructions.EmitLoad(node.TypeOperand);
+                _instructions.EmitTypeEquals();
+            } else {
+                _instructions.EmitTypeIs(node.TypeOperand);
+            }
+        }
+
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")]
+        private void CompileReducibleExpression(Expression expr) {
+            throw new System.NotImplementedException();
+        }
+
+        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
new file mode 100644 (file)
index 0000000..18ce7b9
--- /dev/null
@@ -0,0 +1,194 @@
+/* ****************************************************************************
+ *
+ * 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;
+
+        // Adaptive compilation support:
+        private Type _compiledDelegateType;
+        private Delegate _compiled;
+        private readonly object _compileLock = new object();
+
+        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; }
+        }
+
+        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; }
+        }
+
+        internal Delegate CreateDelegate() {
+            return CreateDelegate(null);
+        }
+
+        internal Delegate CreateDelegate(StrongBox<object>[] closure) {
+            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;
+            }
+
+            // 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;
+            }
+        }
+
+        /// <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;
+            }
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambda.Generated.cs
new file mode 100644 (file)
index 0000000..b3b42a3
--- /dev/null
@@ -0,0 +1,724 @@
+/* ****************************************************************************
+ *
+ * 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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<TRet>)_compiled)();
+            }
+
+            var frame = MakeFrame();
+            var current = frame.Enter();
+            try { _interpreter.Run(frame); } finally { frame.Leave(current); }
+            return (TRet)frame.Pop();
+        }
+
+        internal void RunVoid0() {
+            if (_compiled != null || TryGetCompiled()) {
+                ((Action)_compiled)();
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,TRet>)_compiled)(arg0);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0>)_compiled)(arg0);
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,T1,TRet>)_compiled)(arg0, arg1);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1>)_compiled)(arg0, arg1);
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,T1,T2,TRet>)_compiled)(arg0, arg1, arg2);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1,T2>)_compiled)(arg0, arg1, arg2);
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,T1,T2,T3,TRet>)_compiled)(arg0, arg1, arg2, arg3);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1,T2,T3>)_compiled)(arg0, arg1, arg2, arg3);
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,T1,T2,T3,T4,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1,T2,T3,T4>)_compiled)(arg0, arg1, arg2, arg3, arg4);
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,T1,T2,T3,T4,T5,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1,T2,T3,T4,T5>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,T1,T2,T3,T4,T5,T6,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1,T2,T3,T4,T5,T6>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
+                return;
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1,T2,T3,T4,T5,T6,T7>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
+                return;
+            }
+
+            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 (_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);
+            }
+
+            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 (_compiled != null || TryGetCompiled()) {
+                ((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
+                return;
+            }
+
+            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 (_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);
+            }
+
+            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 (_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;
+            }
+
+            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 (_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);
+            }
+
+            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 (_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;
+            }
+
+            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 (_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);
+            }
+
+            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 (_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;
+            }
+
+            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 (_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);
+            }
+
+            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 (_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;
+            }
+
+            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 (_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);
+            }
+
+            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 (_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;
+            }
+
+            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 (_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);
+            }
+
+            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 (_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;
+            }
+
+            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
new file mode 100644 (file)
index 0000000..94982bf
--- /dev/null
@@ -0,0 +1,272 @@
+/* ****************************************************************************
+ *
+ * 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;
+        private Delegate _compiled;
+        private int _compilationThreshold;
+
+        /// <summary>
+        /// Provides notification that the LightLambda has been compiled.
+        /// </summary>
+        public event EventHandler<LightLambdaCompileEventArgs> Compile;
+
+        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() {
+            // 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
+                }
+            }
+
+            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];
+            }
+        }
+
+        
+        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();
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Interpreter/LightLambdaClosureVisitor.cs
new file mode 100644 (file)
index 0000000..e779e41
--- /dev/null
@@ -0,0 +1,260 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..d848a64
--- /dev/null
@@ -0,0 +1,266 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..acc416e
--- /dev/null
@@ -0,0 +1,323 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..e8b8e98
--- /dev/null
@@ -0,0 +1,46 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..303eb75
--- /dev/null
@@ -0,0 +1,614 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..bb6da75
--- /dev/null
@@ -0,0 +1,276 @@
+/* ****************************************************************************
+ *
+ * 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 {
+    /// <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);
+        }
+    }
+}
\ No newline at end of file
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/MultiRuntimeAwareAttribute.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/MultiRuntimeAwareAttribute.cs
new file mode 100644 (file)
index 0000000..3b0cc25
--- /dev/null
@@ -0,0 +1,34 @@
+/* ****************************************************************************
+ *
+ * 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;
+
+namespace Microsoft.Scripting {
+    /// <summary>
+    /// marks a field, class, or struct as being safe to have statics which can be accessed
+    /// from multiple runtimes.
+    /// 
+    /// Static fields which are not read-only or marked with this attribute will be flagged 
+    /// by a test which looks for state being shared between runtimes.  Before applying this
+    /// attribute you should ensure that it is safe to share the state.  This is typically
+    /// state which is lazy initialized or state which is caching values which are identical
+    /// in all runtimes and are immutable.
+    /// </summary>
+    [Conditional("DEBUG")]
+    [AttributeUsage(AttributeTargets.Field)]   
+    public sealed class MultiRuntimeAwareAttribute : Attribute {
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/PerfTrack.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/PerfTrack.cs
new file mode 100644 (file)
index 0000000..622e41d
--- /dev/null
@@ -0,0 +1,185 @@
+/* ****************************************************************************
+ *
+ * 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 Microsoft.Scripting.Utils;
+using System.Dynamic;
+using System.IO;
+
+namespace Microsoft.Scripting {
+    /// <summary>
+    /// This class is useful for quickly collecting performance counts for expensive
+    /// operations.  Usually this means operations involving either reflection or
+    /// code gen.  Long-term we need to see if this can be plugged better into the
+    /// standard performance counter architecture.
+    /// </summary>
+    public static class PerfTrack {
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1717:OnlyFlagsEnumsShouldHavePluralNames")] // TODO: fix
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] // TODO: fix
+        public enum Categories {
+            /// <summary>
+            /// temporary categories for quick investigation, use a custom key if you
+            /// need to track multiple items, and if you want to keep it then create 
+            /// a new Categories entry and rename all your temporary entries.
+            /// </summary>
+            Temporary,
+            ReflectedTypes,
+            Exceptions,     // exceptions thrown
+            Properties,     // properties got or set
+            Fields,         // fields got or set
+            Methods,        // methods called through MethodBase.Invoke()...
+            Compiler,       // Methods compiled via the ReflectOptimizer
+            DelegateCreate, // we've created a new method for delegates
+            DictInvoke,     // Dictionary accesses
+            OperatorInvoke, // Invoking an operator against a type
+            OverAllocate,   // a spot where we have an un-ideal algorithm that needs to allocate more than necessary
+            Rules,          // related to rules / actions.
+            RuleEvaluation, // a rule was evaluated
+            Binding,        // a rule was bound
+            BindingSlow,
+            BindingFast,    
+            BindingTarget,  // a rule was bound against a target of a specific type
+            Count
+        }
+
+        [MultiRuntimeAware]
+        private static int totalEvents;
+        private static readonly Dictionary<Categories, Dictionary<string, int>> _events = MakeEventsDictionary();
+        private static readonly Dictionary<Categories, int> summaryStats = new Dictionary<Categories, int>();
+
+        private static Dictionary<Categories, Dictionary<string, int>> MakeEventsDictionary() {
+            Dictionary<Categories, Dictionary<string, int>> result = new Dictionary<Categories, Dictionary<string, int>>();
+            
+            // We do not use Enum.GetValues here since it is not available in SILVERLIGHT 
+            for (int i = 0; i <= (int)Categories.Count; i++) {
+                result[(Categories)i] = new Dictionary<string, int>();
+            }
+
+            return result;
+        }
+
+#if FEATURE_BASIC_CONSOLE
+        public static void DumpHistogram<TKey>(IDictionary<TKey, int> histogram) {
+            DumpHistogram(histogram, Console.Out);
+        }
+
+        public static void DumpStats() {
+            DumpStats(Console.Out);
+        }
+#endif
+
+        public static void DumpHistogram<TKey>(IDictionary<TKey, int> histogram, TextWriter output) {
+            var keys = ArrayUtils.MakeArray(histogram.Keys);
+            var values = ArrayUtils.MakeArray(histogram.Values);
+            
+#if !WIN8 // TODO: 
+            Array.Sort(values, keys);
+#endif   
+            for (int i = 0; i < keys.Length; i++) {
+                output.WriteLine("{0} {1}", keys[i], values[i]);
+            }
+        }
+
+        public static void AddHistograms<TKey>(IDictionary<TKey, int> result, IDictionary<TKey, int> addend) {
+            foreach (var entry in addend) {
+                int value;
+                result[entry.Key] = entry.Value + (result.TryGetValue(entry.Key, out value) ? value : 0);
+            }
+        }
+
+        public static void IncrementEntry<TKey>(IDictionary<TKey, int> histogram, TKey key) {
+            int value;
+            histogram.TryGetValue(key, out value);
+            histogram[key] = value + 1;
+        }
+
+        public static void DumpStats(TextWriter output) {
+            if (totalEvents == 0) return;
+
+            // numbers from AMD Opteron 244 1.8 Ghz, 2.00GB of ram,
+            // running on IronPython 1.0 Beta 4 against Whidbey RTM.
+            const double CALL_TIME = 0.0000051442355;
+            const double THROW_TIME = 0.000025365656;
+            const double FIELD_TIME = 0.0000018080093;
+
+            output.WriteLine();
+            output.WriteLine("---- Performance Details ----");
+            output.WriteLine();
+
+            foreach (KeyValuePair<Categories, Dictionary<string, int>> kvpCategories in _events) {
+                if (kvpCategories.Value.Count > 0) {
+                    output.WriteLine("Category : " + kvpCategories.Key);
+                    DumpHistogram(kvpCategories.Value, output);
+                    output.WriteLine();
+                }
+            }
+
+            output.WriteLine();
+            output.WriteLine("---- Performance Summary ----");
+            output.WriteLine();
+            double knownTimes = 0;
+            foreach (KeyValuePair<Categories, int> kvp in summaryStats) {
+                switch (kvp.Key) {
+                    case Categories.Exceptions:
+                        output.WriteLine("Total Exception ({0}) = {1}  (throwtime = ~{2} secs)", kvp.Key, kvp.Value, kvp.Value * THROW_TIME);
+                        knownTimes += kvp.Value * THROW_TIME;
+                        break;
+                    case Categories.Fields:
+                        output.WriteLine("Total field = {0} (time = ~{1} secs)", kvp.Value, kvp.Value * FIELD_TIME);
+                        knownTimes += kvp.Value * FIELD_TIME;
+                        break;
+                    case Categories.Methods:
+                        output.WriteLine("Total calls = {0} (calltime = ~{1} secs)", kvp.Value, kvp.Value * CALL_TIME);
+                        knownTimes += kvp.Value * CALL_TIME;
+                        break;
+                    //case Categories.Properties:
+                    default:
+                        output.WriteLine("Total {1} = {0}", kvp.Value, kvp.Key);
+                        break;
+                }
+            }
+
+            output.WriteLine();
+            output.WriteLine("Total Known Times: {0}", knownTimes);
+        }
+
+        [Conditional("DEBUG")]
+        public static void NoteEvent(Categories category, object key) {
+            if (!DebugOptions.TrackPerformance) return;
+
+            Dictionary<string, int> categoryEvents = _events[category];
+            totalEvents++;
+            lock (categoryEvents) {
+                string name = key.ToString();
+                Exception ex = key as Exception;
+                if (ex != null) name = ex.GetType().ToString();
+                int v;
+                if (!categoryEvents.TryGetValue(name, out v)) categoryEvents[name] = 1;
+                else categoryEvents[name] = v + 1;
+
+                if (!summaryStats.TryGetValue(category, out v)) summaryStats[category] = 1;
+                else summaryStats[category] = v + 1;
+            }
+        }
+    }
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Runtime/ArgumentArray.cs
new file mode 100644 (file)
index 0000000..b6484af
--- /dev/null
@@ -0,0 +1,76 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..378bea4
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..43350e7
--- /dev/null
@@ -0,0 +1,79 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..f7fc8b3
--- /dev/null
@@ -0,0 +1,261 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..4262c15
--- /dev/null
@@ -0,0 +1,354 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..adae9dd
--- /dev/null
@@ -0,0 +1,78 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..57724cc
--- /dev/null
@@ -0,0 +1,114 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..7eaf400
--- /dev/null
@@ -0,0 +1,156 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..dec3b4e
--- /dev/null
@@ -0,0 +1,322 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..53a9ea2
--- /dev/null
@@ -0,0 +1,233 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..3c8e955
--- /dev/null
@@ -0,0 +1,297 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..1214351
--- /dev/null
@@ -0,0 +1,1050 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..8944965
--- /dev/null
@@ -0,0 +1,111 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..13b62d4
--- /dev/null
@@ -0,0 +1,170 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..3d04b8f
--- /dev/null
@@ -0,0 +1,34 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..3b16427
--- /dev/null
@@ -0,0 +1,1229 @@
+/* ****************************************************************************
+ *
+ * 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 !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
+
+        // 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
+
+        #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
+    }
+
+}
diff --git a/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs b/mcs/class/dlr/Runtime/Microsoft.Dynamic/Utils/ReferenceEqualityComparer.cs
new file mode 100644 (file)
index 0000000..291a23e
--- /dev/null
@@ -0,0 +1,48 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..95e23e6
--- /dev/null
@@ -0,0 +1,1951 @@
+/* ****************************************************************************
+ *
+ * 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 static 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\92s 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 \93expect existing slot\94, 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 \93HASTHIS\94 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
new file mode 100644 (file)
index 0000000..934021f
--- /dev/null
@@ -0,0 +1,269 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..c20371d
--- /dev/null
@@ -0,0 +1,375 @@
+/* ****************************************************************************
+ *
+ * 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
+    }
+}
index 5667f889738f527c64347d143d0e55b140da332f..4d1c23567337821fab76fb80fdc5d1feecf47af0 100644 (file)
@@ -19,7 +19,9 @@ 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;
 
@@ -61,9 +63,9 @@ namespace System.Linq.Expressions {
             _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>
@@ -217,11 +219,11 @@ namespace System.Linq.Expressions {
         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);
         }
index 408ae7d99a4aee30b49b69bf5596edfeb909b58b..9a60fa44285a3b7281ae99df68aec78390807621 100644 (file)
@@ -20,7 +20,7 @@ using System.Diagnostics;
 using System.Dynamic.Utils;
 using System.Reflection;
 using System.Runtime.CompilerServices;
-using Microsoft.Scripting.Utils;
+//using Microsoft.Scripting.Utils;
 
 #if !FEATURE_CORE_DLR
 namespace Microsoft.Scripting.Ast {
@@ -207,7 +207,7 @@ namespace System.Linq.Expressions {
             }
             ConstructorInfo ci = null;
             if (!type.IsValueType) {
-                ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, ReflectionUtils.EmptyTypes, null);
+                ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Microsoft.Scripting.Utils.ReflectionUtils.EmptyTypes, null);
                 if (ci == null) {
                     throw Error.TypeMissingDefaultConstructor(type);
                 }
index 95dea78f1fe6d319f9c29c6ee466a3fdd8b7725a..329928fd80ca3f0ddcb6cb1fc9d799903b80b468 100644 (file)
@@ -24,7 +24,9 @@ using System.Linq.Expressions.Compiler;
 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;
@@ -55,6 +57,7 @@ namespace System.Runtime.CompilerServices {
         /// <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);
         }
@@ -62,5 +65,6 @@ namespace System.Runtime.CompilerServices {
         internal virtual void SetLocalName(LocalBuilder localBuilder, string name) {
             // nop
         }
+#endif
     }
 }
index d16f40e4354d8fd2c8362336f877a4a4f46eaf38..a2e5ca0a4c157c1d6e97c17d340b90375fbbaef3 100644 (file)
@@ -16,7 +16,9 @@
 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 {
index 78d5226492ad4d5593af5db4c1bd0f764a71f269..5b219237f66cbd4de81d0807fc3394dbc48ebc30 100644 (file)
@@ -15,7 +15,9 @@
 
 using System.Diagnostics;
 using System.Reflection;
+#if FEATURE_REFEMIT
 using System.Reflection.Emit;
+#endif
 using System.Text;
 
 namespace System.Dynamic.Utils {
@@ -28,13 +30,12 @@ namespace System.Dynamic.Utils {
         /// </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) {
+            if (dm != null)
                 return dm.CreateDelegate(delegateType, target);
-            } else {
-                return Delegate.CreateDelegate(delegateType, target, methodInfo);
-            }
+#endif
+            return Delegate.CreateDelegate(delegateType, target, methodInfo);
         }
 
         internal static Type GetReturnType(this MethodBase mi) {
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting/ArgumentTypeException.cs
new file mode 100644 (file)
index 0000000..5d1e9e2
--- /dev/null
@@ -0,0 +1,38 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..dff8c29
--- /dev/null
@@ -0,0 +1,38 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..d197e8e
--- /dev/null
@@ -0,0 +1,471 @@
+/* ****************************************************************************
+ *
+ * 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();
+
+        public static readonly bool IsCompactFramework =
+#if WIN8
+            false;
+#else
+            Environment.OSVersion.Platform == PlatformID.WinCE ||
+            Environment.OSVersion.Platform == PlatformID.Xbox;
+#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
new file mode 100644 (file)
index 0000000..43cc1af
--- /dev/null
@@ -0,0 +1,40 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..3f0a081
--- /dev/null
@@ -0,0 +1,55 @@
+/* ****************************************************************************
+ *
+ * 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
new file mode 100644 (file)
index 0000000..5719fd9
--- /dev/null
@@ -0,0 +1,116 @@
+/* ****************************************************************************
+ *
+ * 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
\ No newline at end of file
diff --git a/mcs/errors/CS0012-22-lib.il b/mcs/errors/CS0012-22-lib.il
new file mode 100644 (file)
index 0000000..1ee7bd8
--- /dev/null
@@ -0,0 +1,40 @@
+.assembly extern mscorlib
+{
+}
+
+.assembly extern System.Core
+{
+}
+
+.assembly extern 'CS0012-lib-missing'
+{
+}
+
+.assembly 'CS0012-22-lib'
+{
+  .hash algorithm 0x00008004
+  .ver 0:0:0:0
+}
+
+.module 'CS0012-22-lib.dll'
+
+
+.class public abstract auto ansi sealed beforefieldinit B
+       extends [mscorlib]System.Object
+{
+  .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) 
+
+  .method public hidebysig static void
+        Sum(class [mscorlib]System.Collections.Generic.IEnumerable`1<float64> a) cil managed
+  {
+    ret
+  }
+
+  .method public hidebysig static void
+        Sum(class ['CS0012-lib-missing']Base.IQueryExpr`1<class [mscorlib]System.Collections.Generic.IEnumerable`1<float64>> a) cil managed
+  {
+    .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) 
+
+    ret
+  }
+}
index 036f7aee5191e79ae42a6e9579d1cb126d24db7a..6e50c17d37598699b11c666e71d98785397dd112 100644 (file)
@@ -21,7 +21,7 @@ DISTFILES = \
        $(wildcard dlls/second/*.cs)
 
 TEST_SUPPORT_FILES = \
-       CS0012-lib.dll CS0012-2-lib.dll CS0012-3-lib.dll CS0012-4-lib.dll CS0012-5-lib.dll CS0012-6-lib.dll CS0012-9-lib.dll CS0012-10-lib.dll CS0012-11-lib.dll CS0012-12-lib.dll CS0012-13-lib.dll CS0012-14-lib.dll CS0012-15-lib.dll CS0012-16-lib.dll CS0012-17-lib.dll CS0012-18-lib.dll CS0012-21-lib.dll CS0029-26-lib.dll \
+       CS0012-lib.dll CS0012-2-lib.dll CS0012-3-lib.dll CS0012-4-lib.dll CS0012-5-lib.dll CS0012-6-lib.dll CS0012-9-lib.dll CS0012-10-lib.dll CS0012-11-lib.dll CS0012-12-lib.dll CS0012-13-lib.dll CS0012-14-lib.dll CS0012-15-lib.dll CS0012-16-lib.dll CS0012-17-lib.dll CS0012-18-lib.dll CS0012-21-lib.dll CS0012-22-lib.dll CS0029-26-lib.dll \
        CS0103-2-lib.dll CS0118-2-lib.dll CS0122-8-lib.dll CS0122-10-lib.dll CS0122-14-lib.dll CS0122-15-lib.dll CS0122-19-lib.dll CS0122-35-lib.dll CS0122-36-lib.dll CS0143-lib.dll CS0144-3-lib.dll CS0165-19-lib.dll \
        CS0205-3-lib.dll CS0246-29-lib.dll CS0229-3-lib.dll CS0229-4-lib.dll CS0266-25-lib.dll \
        CS0315-2-lib.dll \
diff --git a/mcs/errors/cs0012-22.cs b/mcs/errors/cs0012-22.cs
new file mode 100644 (file)
index 0000000..3d4bd78
--- /dev/null
@@ -0,0 +1,11 @@
+// CS0012: The type `Base.IQueryExpr`1<System.Collections.Generic.IEnumerable<double>>' is defined in an assembly that is not referenced. Consider adding a reference to assembly `CS0012-lib-missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
+// Line: 9
+// Compiler options: -r:CS0012-22-lib.dll
+
+public class C
+{
+       public static void Main ()
+       {
+               B.Sum (null);
+       }
+}
\ No newline at end of file
diff --git a/mcs/errors/cs0029-35.cs b/mcs/errors/cs0029-35.cs
new file mode 100644 (file)
index 0000000..c233099
--- /dev/null
@@ -0,0 +1,12 @@
+// CS0029: Cannot implicitly convert type `string' to `int'
+// Line: 10
+// Compiler options: -unsafe
+
+class TestClass
+{
+       public unsafe static void Main ()
+       {
+               int* arr = null;
+               var i = arr["c"];
+       }
+}
\ No newline at end of file
diff --git a/mcs/errors/cs0165-44.cs b/mcs/errors/cs0165-44.cs
new file mode 100644 (file)
index 0000000..d4b6988
--- /dev/null
@@ -0,0 +1,21 @@
+// CS0165: Use of unassigned local variable `x'
+// Line: 19
+
+struct S
+{
+       public object O;
+}
+
+class X
+{
+       public S s;
+}
+
+class C
+{
+       public static void Main ()
+       {
+               X x;
+               x.s.O = 2;
+       }
+}
\ No newline at end of file
diff --git a/mcs/errors/cs0220-4.cs b/mcs/errors/cs0220-4.cs
new file mode 100644 (file)
index 0000000..c52aa54
--- /dev/null
@@ -0,0 +1,12 @@
+// CS0220: The operation overflows at compile time in checked mode
+// Line: 10
+// Compiler options: -unsafe
+
+class TestClass
+{
+       public unsafe static void Main ()
+       {
+               int* arr = null;
+               var i = arr[long.MaxValue];
+       }
+}
\ No newline at end of file
diff --git a/mcs/errors/cs1060-4.cs b/mcs/errors/cs1060-4.cs
new file mode 100644 (file)
index 0000000..f811f51
--- /dev/null
@@ -0,0 +1,32 @@
+// CS1060: Use of possibly unassigned field `x'
+// Line: 30
+// Compiler options: -warnaserror
+
+public class C
+{
+       public int v;
+}
+
+public struct S
+{
+       public C c;
+}
+
+class X
+{
+       public S s;
+}
+
+struct S2
+{
+       public X x;
+}
+
+public class Test
+{
+       static void Main ()
+       {
+               S2 s2;
+               s2.x.s.c.v = 5;
+       }
+}
diff --git a/mcs/errors/cs1654-5.cs b/mcs/errors/cs1654-5.cs
new file mode 100644 (file)
index 0000000..fbabd02
--- /dev/null
@@ -0,0 +1,16 @@
+// CS1654: Cannot assign to members of `p' because it is a `foreach iteration variable'
+// Line: 14
+
+using System.Collections;
+
+struct P {
+       public int x { get; set; }
+}
+
+class Test {
+       static void Foo (IEnumerable f)
+       {
+               foreach (P p in f)
+                       p.x += 2;
+       }
+}
index a2f951235f75fc19955fb37374a3c73c59602f78..1e07f7c667ee0b12c339540088bf027700452b7b 100644 (file)
@@ -17,7 +17,3 @@ cs0080.cs
 # Operators
 cs0457-2.cs
 cs0457.cs
-
-cs1060.cs NO ERROR
-cs1060-2.cs NO ERROR
-cs1060-3.cs NO ERROR
index 714e953be0052518939d5d21d537479379568620..9481aef96edae4b6d66b28b161a9eeb43e0b5b44 100644 (file)
@@ -363,7 +363,7 @@ namespace Mono.CSharp {
                        return this;
                }
 
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
                {
                        var tassign = target as IDynamicAssign;
index 5ab84f260afd3ae85e8d9c6ee75f1e70c1582a97..8cbaeff0c5464d7956eebd1f5039ffa632e52e83 100644 (file)
@@ -97,6 +97,9 @@ namespace Mono.CSharp
                        if (rc.HasSet (ResolveContext.Options.CheckedScope))
                                flags |= ResolveContext.Options.CheckedScope;
 
+                       if (!rc.ConstantCheckState)
+                               flags &= ~Options.ConstantCheckState;
+
                        if (rc.IsInProbingMode)
                                flags |= ResolveContext.Options.ProbingMode;
 
index ad1853a4a4ea530bf1bb1d25ff27c468477487ca..9f55f368256aae961d4d26d2154aa6a9807b8143 100644 (file)
@@ -328,6 +328,7 @@ namespace Mono.CSharp
                        tr.Start (TimeReporter.TimerType.CreateTypeTotal);
                        module.CreateContainer ();
                        importer.AddCompiledAssembly (assembly);
+                       references_loader.CompiledAssembly = assembly;
                        tr.Stop (TimeReporter.TimerType.CreateTypeTotal);
 
                        references_loader.LoadReferences (module);
index 3627610a51c14cc7f27e59b99dd119992220a902..939984e5c6b41e972d3ce4e8facebc77bf89b276 100644 (file)
@@ -13,7 +13,7 @@ using System;
 using System.Linq;
 using SLE = System.Linq.Expressions;
 
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
 using System.Dynamic;
 #endif
 
@@ -63,7 +63,7 @@ namespace Mono.CSharp
        //
        public class RuntimeValueExpression : Expression, IDynamicAssign, IMemoryLocation
        {
-#if !NET_4_0 && !MONODROID
+#if !NET_4_0 && !MOBILE_DYNAMIC
                public class DynamicMetaObject
                {
                        public TypeSpec RuntimeType;
@@ -146,7 +146,7 @@ namespace Mono.CSharp
                        return base.MakeExpression (ctx);
 #else
 
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                                if (type.IsStruct && !obj.Expression.Type.IsValueType)
                                        return SLE.Expression.Unbox (obj.Expression, type.GetMetaInfo ());
 
@@ -181,7 +181,7 @@ namespace Mono.CSharp
                        return this;
                }
 
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
 #if STATIC
index ec0d7a2c60670ce1f4f3caea3dafab0ad30461a8..3bad645c309f5b2fad893b8d33c69a1f40a7f893 100644 (file)
@@ -1058,7 +1058,7 @@ namespace Mono.CSharp {
                //
                // Converts `source' to an int, uint, long or ulong.
                //
-               protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source)
+               protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source, bool pointerArray = false)
                {
                        var btypes = ec.BuiltinTypes;
 
@@ -1085,6 +1085,9 @@ namespace Mono.CSharp {
                                }
                        }
 
+                       if (pointerArray)
+                               return converted;
+
                        //
                        // Only positive constants are allowed at compile time
                        //
@@ -5811,25 +5814,36 @@ namespace Mono.CSharp {
                        }
 
                        var fe = InstanceExpression as FieldExpr;
-                       if (fe != null || lvalue_instance) {
-                               if (fe == null)
-                                       return;
+                       if (fe != null) {
+                               Expression instance;
 
-                               /*
-                               while (fe.InstanceExpression is FieldExpr) {
-                                       fe = (FieldExpr) fe.InstanceExpression;
-                                       if (!fe.Spec.DeclaringType.IsStruct)
-                                               continue;
+                               do {
+                                       instance = fe.InstanceExpression;
+                                       var fe_instance = instance as FieldExpr;
+                                       if ((fe_instance != null && !fe_instance.IsStatic) || instance is LocalVariableReference) {
+                                               if (TypeSpec.IsReferenceType (fe.Type) && instance.Type.IsStruct) {
+                                                       var var = InstanceExpression as IVariableReference;
+                                                       if (var != null && var.VariableInfo == null) {
+                                                               var var_inst = instance as IVariableReference;
+                                                               if (var_inst == null || (var_inst.VariableInfo != null && !fc.IsDefinitelyAssigned (var_inst.VariableInfo)))
+                                                                       fc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
+                                                       }
+                                               }
 
-                                       if (fe.VariableInfo != null && fc.IsStructFieldDefinitelyAssigned (fe.VariableInfo, fe.Name)) {
-                                               fc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
+                                               if (fe_instance != null) {
+                                                       fe = fe_instance;
+                                                       continue;
+                                               }
                                        }
-                               }
 
-                               fe.InstanceExpression.FlowAnalysis (fc);
-                               */
+                                       break;
+                               } while (true);
+
+                               if (instance != null && TypeSpec.IsReferenceType (instance.Type))
+                                       instance.FlowAnalysis (fc);
                        } else {
-                               InstanceExpression.FlowAnalysis (fc);
+                               if (TypeSpec.IsReferenceType (InstanceExpression.Type))
+                                       InstanceExpression.FlowAnalysis (fc);
                        }
                }
 
@@ -6522,6 +6536,8 @@ namespace Mono.CSharp {
 
                                if (expr != this)
                                        return expr.ResolveLValue (ec, right_side);
+                       } else {
+                               ResolveInstanceExpression (ec, right_side);
                        }
 
                        if (!ResolveSetter (ec))
index 3458f7499c937c8ecdf5a468035f02ec7ae1ced0..766bb05696b6f9e815d0b80ee621c3e1c54194f7 100644 (file)
@@ -1046,9 +1046,7 @@ namespace Mono.CSharp
                static public string help {
                        get {
                                return "Static methods:\n" +
-#if !NET_2_1
                                        "  Describe (object);       - Describes the object's type\n" +
-#endif
                                        "  LoadPackage (package);   - Loads the given Package (like -pkg:FILE)\n" +
                                        "  LoadAssembly (assembly); - Loads the given assembly (like -r:ASSEMBLY)\n" +
                                        "  ShowVars ();             - Shows defined local variables.\n" +
index dfec547a0ba4d471a859ef34eff3a5f34639a355..de639d70ce694a6d94c6e9af9556291970b28d01 100644 (file)
@@ -657,7 +657,7 @@ namespace Mono.CSharp
                                return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
                        case Operator.LogicalNot:
                                return SLE.Expression.Not (expr);
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                        case Operator.OnesComplement:
                                return SLE.Expression.OnesComplement (expr);
 #endif
@@ -1340,7 +1340,7 @@ namespace Mono.CSharp
                }
 
 
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
                        var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
@@ -1922,7 +1922,7 @@ namespace Mono.CSharp
                        temp_storage.Release (ec);
                }
 
-#if (NET_4_0 || MONODROID) && !STATIC
+#if (NET_4_0 || MOBILE_DYNAMIC) && !STATIC
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
                        return SLE.Expression.Default (type.GetMetaInfo ());
@@ -7421,7 +7421,7 @@ namespace Mono.CSharp
                        return data;
                }
 
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
 #if STATIC
@@ -9306,17 +9306,24 @@ namespace Mono.CSharp
                        return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
                }
 
-               Expression MakePointerAccess (ResolveContext ec, TypeSpec type)
+               Expression MakePointerAccess (ResolveContext rc, TypeSpec type)
                {
                        if (Arguments.Count != 1){
-                               ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
+                               rc.Report.Error (196, loc, "A pointer must be indexed by only one value");
                                return null;
                        }
 
-                       if (Arguments [0] is NamedArgument)
-                               Error_NamedArgument ((NamedArgument) Arguments[0], ec.Report);
+                       var arg = Arguments[0];
+                       if (arg is NamedArgument)
+                               Error_NamedArgument ((NamedArgument) arg, rc.Report);
 
-                       Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, Arguments [0].Expr.Resolve (ec), type, loc);
+                       var index = arg.Expr.Resolve (rc);
+                       if (index == null)
+                               return null;
+
+                       index = ConvertExpressionToArrayIndex (rc, index, true);
+
+                       Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, index, type, loc);
                        return new Indirection (p, loc);
                }
                
@@ -9611,7 +9618,7 @@ namespace Mono.CSharp
 
                public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
                {
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                        return SLE.Expression.ArrayAccess (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
 #else
                        throw new NotImplementedException ();
@@ -9790,7 +9797,7 @@ namespace Mono.CSharp
 #else
                        var value = new[] { source.MakeExpression (ctx) };
                        var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                        return SLE.Expression.Block (
                                        SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
                                        value [0]);
index 1a74b3148e5014df63adc4a1c3f7154b086352e2..0d3232c75ae40e4a1f69cf54059a031515b54988 100644 (file)
@@ -285,6 +285,8 @@ namespace Mono.CSharp
                        }
                }
 
+               public AssemblyDefinitionStatic CompiledAssembly {  get; set; }
+
                public Universe Domain {
                        get {
                                return domain;
@@ -368,6 +370,14 @@ namespace Mono.CSharp
                                return version_mismatch;
                        }
 
+                       //
+                       // Recursive reference to compiled assembly checks name only. Any other
+                       // details (PublicKey, Version, etc) are not yet known hence cannot be checked
+                       //
+                       ParsedAssemblyName referenced_assembly;
+                       if (Fusion.ParseAssemblyName (args.Name, out referenced_assembly) == ParseAssemblyResult.OK && CompiledAssembly.Name == referenced_assembly.Name)
+                               return CompiledAssembly.Builder;
+
                        // AssemblyReference has not been found in the domain
                        // create missing reference and continue
                        return domain.CreateMissingAssembly (args.Name);
index 125404f6d920693b7289b968bde5a15fae1ff9c1..f71647968d5edcf69c6bd1dfed19ab3185fd1af4 100644 (file)
@@ -75,15 +75,24 @@ namespace Mono.CSharp
                                return flags != null;
                        }
 
+                       IList<CustomAttributeData> GetCustomAttributes ()
+                       {
+                               var mi = provider as MemberInfo;
+                               if (mi != null)
+                                       return CustomAttributeData.GetCustomAttributes (mi);
+
+                               var pi = provider as ParameterInfo;
+                               if (pi != null)
+                                       return CustomAttributeData.GetCustomAttributes (pi);
+
+                               provider = null;
+                               return null;
+                       }
+
                        void ReadAttribute ()
                        {
-                               IList<CustomAttributeData> cad;
-                               if (provider is MemberInfo) {
-                                       cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
-                               } else if (provider is ParameterInfo) {
-                                       cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
-                               } else {
-                                       provider = null;
+                               var cad = GetCustomAttributes ();
+                               if (cad == null) {
                                        return;
                                }
 
@@ -493,7 +502,7 @@ namespace Mono.CSharp
                                } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
                                        HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
                                        mod = Parameter.Modifier.This;
-                                       types[i] = ImportType (p.ParameterType);
+                                       types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
                                } else {
                                        types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
 
@@ -1150,6 +1159,14 @@ namespace Mono.CSharp
                                throw new NotImplementedException ("Unknown element type " + type.ToString ());
                        }
 
+                       TypeSpec compiled_type;
+                       if (compiled_types.TryGetValue (type, out compiled_type)) {
+                               if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
+                                       return module.Compiler.BuiltinTypes.Dynamic;
+
+                               return compiled_type;
+                       }
+
                        return CreateType (type, dtype, true);
                }
 
index 10afaa1cc263a97ef0ff931eaaa422d01a822619..e7daa53ce0bd98a5f86aeba6f18d632b7f65690f 100644 (file)
@@ -222,7 +222,7 @@ namespace Mono.CSharp
                // </summary>
                static public void Initialize (List<SourceFile> files)
                {
-#if NET_4_0 || MONODROID
+#if NET_4_0 || MOBILE_DYNAMIC
                        source_list.AddRange (files);
 #else
                        source_list.AddRange (files.ToArray ());
index 89e94af3963898f878f9b26d0980e9b7b7b0017c..5b9d6e647917f0b523ba5af10171a49c7a928f9c 100644 (file)
@@ -464,6 +464,7 @@ namespace Mono.CSharp {
                        IList<MemberSpec> applicable;
                        TypeSpec best_match = null;
                        do {
+#if !FULL_AOT_RUNTIME
                                // TODO: Don't know how to handle this yet
                                // When resolving base type of nested type, parent type must have
                                // base type resolved to scan full hierarchy correctly
@@ -472,6 +473,7 @@ namespace Mono.CSharp {
                                var tc = container.MemberDefinition as TypeContainer;
                                if (tc != null)
                                        tc.DefineContainer ();
+#endif
 
                                if (container.MemberCacheTypes.member_hash.TryGetValue (name, out applicable)) {
                                        for (int i = applicable.Count - 1; i >= 0; i--) {
index 411416712ad368e275b30ec310760b553b0b872f..b233b9439cbfd397d52a28c70953d10d3ab8564e 100644 (file)
@@ -219,7 +219,7 @@ namespace Mono.CSharp
                //
                public bool Create (AppDomain domain, AssemblyBuilderAccess access)
                {
-#if STATIC
+#if STATIC || FULL_AOT_RUNTIME
                        throw new NotSupportedException ();
 #else
                        ResolveAssemblySecurityAttributes ();
index 7090c4a7aefb05e22389c3728c0b2250e10bd39b..160431030e0d1f7a06aa9197846e5123b6e63326 100644 (file)
@@ -6748,10 +6748,12 @@ namespace Mono.CSharp {
                                                return;
                                        }
 
-                                       bc.Report.SymbolRelatedToPreviousError (type);
-                                       var loc = type_expr == null ? initializer.Location : type_expr.Location;
-                                       bc.Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
-                                               type.GetSignatureForError ());
+                                       if (type != InternalType.ErrorType) {
+                                               bc.Report.SymbolRelatedToPreviousError (type);
+                                               var loc = type_expr == null ? initializer.Location : type_expr.Location;
+                                               bc.Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
+                                                       type.GetSignatureForError ());
+                                       }
 
                                        return;
                                }
index 8cbbc14680557a301ba3dcb59834d1b2f8c09012..be2f6a48583cfee7c23627d640ad7d46d0f22024 100644 (file)
@@ -36,7 +36,7 @@ namespace Mono.CSharp {
                        return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode (obj);
                }
        }
-#if !NET_4_0 && !MONODROID
+#if !NET_4_0 && !MOBILE_DYNAMIC
        public class Tuple<T1, T2> : IEquatable<Tuple<T1, T2>>
        {
                public Tuple (T1 item1, T2 item2)
index b0a932eb4f9f77f89dc060317ca77501c0e1133c..33925e7df282c7380770f962b61223024d5b71f3 100644 (file)
@@ -96,3 +96,4 @@ csproj-local:
 setup:
        $(CSCOMPILE) -t:library dlls/test-679-2/test-679-lib-2.cs
        $(CSCOMPILE) -t:library dlls/test-679-1/test-679-lib.cs -r:dlls/test-679-2/test-679-lib-2.dll
+       $(ILASM) -dll dlls/test-883.il
diff --git a/mcs/tests/dlls/test-883.il b/mcs/tests/dlls/test-883.il
new file mode 100644 (file)
index 0000000..d6b1fc4
--- /dev/null
@@ -0,0 +1,27 @@
+.assembly extern mscorlib
+{
+}
+
+.assembly 'test-883'
+{
+  .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00   // .$..............
+                00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00   // .$..RSA1........
+                79 15 99 77 D2 D0 3A 8E 6B EA 7A 2E 74 E8 D1 AF   // y..w..:.k.z.t...
+                CC 93 E8 85 19 74 95 2B B4 80 A1 2C 91 34 47 4D   // .....t.+...,.4GM
+                04 06 24 47 C3 7E 0E 68 C0 80 53 6F CF 3C 3F BE   // ..$G.~.h..So.<?.
+                2F F9 C9 79 CE 99 84 75 E5 06 E8 CE 82 DD 5B 0F   // /..y...u......[.
+                35 0D C1 0E 93 BF 2E EE CF 87 4B 24 77 0C 50 81   // 5.........K$w.P.
+                DB EA 74 47 FD DA FA 27 7B 22 DE 47 D6 FF EA 44   // ..tG...'{".G...D
+                96 74 A4 F9 FC CF 84 D1 50 69 08 93 80 28 4D BD   // .t......Pi...(M.
+                D3 5F 46 CD FF 12 A1 BD 78 E4 EF 00 65 D0 16 DF ) // ._F.....x...e...
+  .hash algorithm 0x00008004
+  .ver 2:0:0:0
+}
+.module 'test-883.dll'
+
+.class public auto ansi sealed E
+       extends [mscorlib]System.Enum
+{
+  .field public specialname rtspecialname int32 value__
+  .field public static literal valuetype E TestField = int32(0x00000003)
+}
diff --git a/mcs/tests/gtest-lambda-32.cs b/mcs/tests/gtest-lambda-32.cs
new file mode 100644 (file)
index 0000000..a46f1e4
--- /dev/null
@@ -0,0 +1,13 @@
+using System;
+
+class X
+{
+       const int Value = 1000;
+
+       static void Main ()
+       { 
+               unchecked { 
+                       Func<byte> b = () => (byte)X.Value;
+               } 
+       }
+}
\ No newline at end of file
index 6a7e2c8a9c5cc6fa968b227c45511f5317a1d609..d5c83a033f9cbe9bbf5ddc45cc7d0b817684ddc5 100644 (file)
@@ -23,6 +23,18 @@ class C
                        s.F = 1.0f;
                }
        }
+
+       static void Test2 (bool b)
+       {
+               S s;
+               if (b) {
+                       s.s2 = new S2 ();
+                       s.F = 1.0f;
+               } else {
+                       s.s2.f1 = 2.1f;
+                       s.F = 1.0f;
+               }
+       }
        
        public static int Main ()
        {
diff --git a/mcs/tests/test-883-lib.cs b/mcs/tests/test-883-lib.cs
new file mode 100644 (file)
index 0000000..643f613
--- /dev/null
@@ -0,0 +1,8 @@
+// Compiler options: -t:library -r:dlls/test-883.dll
+
+public class TestClass
+{
+       public static void Foo (E e)
+       {
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-883.cs b/mcs/tests/test-883.cs
new file mode 100644 (file)
index 0000000..63d6e20
--- /dev/null
@@ -0,0 +1,14 @@
+// Compiler options: -r:test-883-lib.dll -t:library
+
+public enum E
+{
+       TestField = 3
+}
+
+public class Second
+{
+       public void TestFinal ()
+       {
+               TestClass.Foo (E.TestField);
+       }
+}
index f98a0475acfa160a77036fbdfd681b2b3c6b7cf8..3e2ae6cfb5180fa70b7ce8e75e273b30b9485b14 100644 (file)
       </method>\r
     </type>\r
   </test>\r
+  <test name="gtest-lambda-32.cs">\r
+    <type name="X">\r
+      <method name="Void Main()" attrs="145">\r
+        <size>34</size>\r
+      </method>\r
+      <method name="Byte &lt;Main&gt;m__0()" attrs="145">\r
+        <size>13</size>\r
+      </method>\r
+      <method name="Void .ctor()" attrs="6278">\r
+        <size>7</size>\r
+      </method>\r
+    </type>\r
+  </test>\r
   <test name="gtest-linq-01.cs">\r
     <type name="from.C">\r
       <method name="Void Main()" attrs="150">\r
   <test name="test-401.cs">\r
     <type name="X">\r
       <method name="Int32 Main()" attrs="150">\r
-        <size>207</size>\r
+        <size>206</size>\r
       </method>\r
       <method name="Void .ctor()" attrs="6278">\r
         <size>7</size>\r
       <method name="Void .ctor()" attrs="6278">\r
         <size>7</size>\r
       </method>\r
+      <method name="Void Test2(Boolean)" attrs="145">\r
+        <size>74</size>\r
+      </method>\r
     </type>\r
   </test>\r
   <test name="test-83.cs">\r
index 72c6da574e7a8908a37c9545651bc81909b3593d..2dc4bcebb3d99ef9ce3a736184c98627b0dda979 100644 (file)
@@ -1231,6 +1231,9 @@ namespace CorCompare
 
                static object GetFlaggedEnumValue (TypeDefinition type, object value)
                {
+                       if (value is ulong)
+                               return GetFlaggedEnumValue (type, (ulong)value);
+
                        long flags = Convert.ToInt64 (value);
                        var signature = new StringBuilder ();
 
@@ -1257,6 +1260,33 @@ namespace CorCompare
                        return signature.ToString ();
                }
 
+               static object GetFlaggedEnumValue (TypeDefinition type, ulong flags)
+               {
+                       var signature = new StringBuilder ();
+
+                       for (int i = type.Fields.Count - 1; i >= 0; i--) {
+                               FieldDefinition field = type.Fields [i];
+
+                               if (!field.HasConstant)
+                                       continue;
+
+                               ulong flag = Convert.ToUInt64 (field.Constant);
+
+                               if (flag == 0)
+                                       continue;
+
+                               if ((flags & flag) == flag) {
+                                       if (signature.Length != 0)
+                                               signature.Append (", ");
+
+                                       signature.Append (field.Name);
+                                       flags -= flag;
+                               }
+                       }
+
+                       return signature.ToString ();
+               }
+
                static object GetEnumValue (TypeDefinition type, object value)
                {
                        foreach (FieldDefinition field in type.Fields) {
index abdaed2d135dfacb23760b91f23414e075e00228..5083e6f28c594633232f14012fb1b9321c9e0c7e 100644 (file)
@@ -8,6 +8,7 @@
 //
 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
+// Copyright 2011-2013 Xamarin Inc
 //
 //
 // TODO:
@@ -34,6 +35,8 @@ namespace Mono {
        public class Driver {
                public static string StartupEvalExpression;
                static int? attach;
+               static string target_host;
+               static int target_port;
                static string agent;
                
                static int Main (string [] args)
@@ -73,15 +76,17 @@ namespace Mono {
                        CSharpShell shell;
 #if !ON_DOTNET
                        if (attach.HasValue) {
-                               shell = new ClientCSharpShell (eval, attach.Value);
+                               shell = new ClientCSharpShell_v1 (eval, attach.Value);
                        } else if (agent != null) {
                                new CSharpAgent (eval, agent, agent_stderr).Run (startup_files);
                                return 0;
                        } else
 #endif
-                       {
+                       if (target_host != null) 
+                               shell = new ClientCSharpShell  (eval, target_host, target_port);
+                       else 
                                shell = new CSharpShell (eval);
-                       }
+
                        return shell.Run (startup_files);
                }
 
@@ -101,6 +106,26 @@ namespace Mono {
                                }
                                break;
                        default:
+                               if (args [pos].StartsWith ("--server=")){
+                                       var hostport = args [pos].Substring (9);
+                                       int p = hostport.IndexOf (':');
+                                       if (p == -1){
+                                               target_host = hostport;
+                                               target_port = 10000;
+                                       } else {
+                                               target_host = hostport.Substring (0,p);
+                                               if (!int.TryParse (hostport.Substring (p), out target_port)){
+                                                       Console.Error.WriteLine ("Usage is: --server[=host[:port]");
+                                                       Environment.Exit (1);
+                                               }
+                                       }
+                                       return pos + 1;
+                               }
+                               if (args [pos].StartsWith ("--client")){
+                                       target_host = "localhost";
+                                       target_port = 10000;
+                                       return pos + 1;
+                               }
                                if (args [pos].StartsWith ("--agent:")) {
                                        agent = args[pos];
                                        return pos + 1;
@@ -513,6 +538,162 @@ namespace Mono {
                
        }
 
+       //
+       // Stream helper extension methods
+       //
+       public static class StreamHelper {
+               static DataConverter converter = DataConverter.LittleEndian;
+               
+               static void GetBuffer (this Stream stream, byte [] b)
+               {
+                       int n, offset = 0;
+                       int len = b.Length;
+
+                       do {
+                               n = stream.Read (b, offset, len);
+                               if (n == 0)
+                                       throw new IOException ("End reached");
+
+                               offset += n;
+                               len -= n;
+                       } while (len > 0);
+               }
+
+               public static int GetInt (this Stream stream)
+               {
+                       byte [] b = new byte [4];
+                       stream.GetBuffer (b);
+                       return converter.GetInt32 (b, 0);
+               }
+
+               public static string GetString (this Stream stream)
+               {
+                       int len = stream.GetInt ();
+                       if (len == 0)
+                               return "";
+
+                       byte [] b = new byte [len];
+                       stream.GetBuffer (b);
+
+                       return Encoding.UTF8.GetString (b);
+               }
+
+               public static void WriteInt (this Stream stream, int n)
+               {
+                       byte [] bytes = converter.GetBytes (n);
+                       stream.Write (bytes, 0, bytes.Length);
+               }
+       
+               public static void WriteString (this Stream stream, string s)
+               {
+                       stream.WriteInt (s.Length);
+                       byte [] bytes = Encoding.UTF8.GetBytes (s);
+                       stream.Write (bytes, 0, bytes.Length);
+               }
+       }
+       
+       public enum AgentStatus : byte {
+               // Received partial input, complete
+               PARTIAL_INPUT  = 1,
+       
+               // The result was set, expect the string with the result
+               RESULT_SET     = 2,
+       
+               // No result was set, complete
+               RESULT_NOT_SET = 3,
+       
+               // Errors and warnings string follows
+               ERROR          = 4,
+
+               // Stdout
+               STDOUT         = 5,
+       }
+
+       class ClientCSharpShell : CSharpShell {
+               string target_host;
+               int target_port;
+               
+               public ClientCSharpShell (Evaluator evaluator, string target_host, int target_port) : base (evaluator)
+               {
+                       this.target_port = target_port;
+                       this.target_host = target_host;
+               }
+
+               T ConnectServer<T> (Func<NetworkStream,T> callback, Action<Exception> error)
+               {
+                       try {
+                               var client = new TcpClient (target_host, target_port);
+                               var ns = client.GetStream ();
+                               T ret = callback (ns);
+                               ns.Flush ();
+                               ns.Close ();
+                               client.Close ();
+                               return ret;
+                       } catch (Exception e){
+                               error (e);
+                               return default(T);
+                       }
+               }
+               
+               protected override string Evaluate (string input)
+               {
+                       return ConnectServer<string> ((ns)=> {
+                               try {
+                                       ns.WriteString ("EVALTXT");
+                                       ns.WriteString (input);
+
+                                       while (true) {
+                                               AgentStatus s = (AgentStatus) ns.ReadByte ();
+                                       
+                                               switch (s){
+                                               case AgentStatus.PARTIAL_INPUT:
+                                                       return input;
+                                               
+                                               case AgentStatus.ERROR:
+                                                       string err = ns.GetString ();
+                                                       Console.Error.WriteLine (err);
+                                                       break;
+
+                                               case AgentStatus.STDOUT:
+                                                       string stdout = ns.GetString ();
+                                                       Console.WriteLine (stdout);
+                                                       break;
+                                               
+                                               case AgentStatus.RESULT_NOT_SET:
+                                                       return null;
+                                               
+                                               case AgentStatus.RESULT_SET:
+                                                       string res = ns.GetString ();
+                                                       Console.WriteLine (res);
+                                                       return null;
+                                               }
+                                       }
+                               } catch (Exception e){
+                                       Console.Error.WriteLine ("Error evaluating expression, exception: {0}", e);
+                               }
+                               return null;
+                       }, (e) => {
+                               Console.Error.WriteLine ("Error communicating with server {0}", e);
+                       });
+               }
+               
+               public override int Run (string [] startup_files)
+               {
+                       // The difference is that we do not call Evaluator.Init, that is done on the target
+                       this.startup_files = startup_files;
+                       return ReadEvalPrintLoop ();
+               }
+       
+               protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
+               {
+                       ConnectServer<int> ((ns)=> {
+                               ns.WriteString ("INTERRUPT");
+                               return 0;
+                       }, (e) => { });
+               }
+                       
+       }
+
 #if !ON_DOTNET
        //
        // A shell connected to a CSharpAgent running in a remote process.
@@ -520,10 +701,10 @@ namespace Mono {
        //  - Support Gtk and Winforms main loops if detected, this should
        //    probably be done as a separate agent in a separate place.
        //
-       class ClientCSharpShell : CSharpShell {
+       class ClientCSharpShell_v1 : CSharpShell {
                NetworkStream ns, interrupt_stream;
                
-               public ClientCSharpShell (Evaluator evaluator, int pid)
+               public ClientCSharpShell_v1 (Evaluator evaluator, int pid)
                        : base (evaluator)
                {
                        // Create a server socket we listen on whose address is passed to the agent
@@ -548,7 +729,7 @@ namespace Mono {
        
                        Console.WriteLine ("Connected.");
                }
-       
+
                //
                // A remote version of Evaluate
                //
@@ -598,57 +779,6 @@ namespace Mono {
                        
        }
 
-       //
-       // Stream helper extension methods
-       //
-       public static class StreamHelper {
-               static DataConverter converter = DataConverter.LittleEndian;
-               
-               public static int GetInt (this Stream stream)
-               {
-                       byte [] b = new byte [4];
-                       if (stream.Read (b, 0, 4) != 4)
-                               throw new IOException ("End reached");
-                       return converter.GetInt32 (b, 0);
-               }
-               
-               public static string GetString (this Stream stream)
-               {
-                       int len = stream.GetInt ();
-                       byte [] b = new byte [len];
-                       if (stream.Read (b, 0, len) != len)
-                               throw new IOException ("End reached");
-                       return Encoding.UTF8.GetString (b);
-               }
-       
-               public static void WriteInt (this Stream stream, int n)
-               {
-                       byte [] bytes = converter.GetBytes (n);
-                       stream.Write (bytes, 0, bytes.Length);
-               }
-       
-               public static void WriteString (this Stream stream, string s)
-               {
-                       stream.WriteInt (s.Length);
-                       byte [] bytes = Encoding.UTF8.GetBytes (s);
-                       stream.Write (bytes, 0, bytes.Length);
-               }
-       }
-       
-       public enum AgentStatus : byte {
-               // Received partial input, complete
-               PARTIAL_INPUT  = 1,
-       
-               // The result was set, expect the string with the result
-               RESULT_SET     = 2,
-       
-               // No result was set, complete
-               RESULT_NOT_SET = 3,
-       
-               // Errors and warnings string follows
-               ERROR          = 4, 
-       }
-       
        //
        // This is the agent loaded into the target process when using --attach.
        //
diff --git a/mcs/tools/linker/Descriptors/System.Core.xml b/mcs/tools/linker/Descriptors/System.Core.xml
new file mode 100644 (file)
index 0000000..e5a547f
--- /dev/null
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<linker>
+       <assembly fullname="System.Core">
+               <type fullname="System.Runtime.CompilerServices.CallSiteOps" preserve="methods" feature="dynamic" />
+       </assembly>
+</linker>
index 692976b709ff83edc5561f29088db6f03a15dbae..b6b8fc785611d4f43ed16e58922940a3c7140535 100644 (file)
@@ -9,6 +9,7 @@ CECIL = $(topdir)/class/lib/$(PROFILE)/Mono.Cecil.dll
 RESOURCES = \
        Descriptors/mscorlib.xml        \
        Descriptors/System.xml          \
+       Descriptors/System.Core.xml             \
        Descriptors/System.Drawing.xml  \
        Descriptors/System.Web.xml              \
        Descriptors/Mono.Posix.xml              \
index 34371de220f4733319b92298ecf032d69d5e575b..749b77506bbdf6667df67edfe9e6be9beee9aabf 100644 (file)
@@ -105,6 +105,10 @@ Here is an example that shows all the possibilities of this format:
 
 In this example, the linker will link the types Foo, Bar, Baz and Gazonk.
 
+The fullname attribute specifies the fullname of the type in the format
+specified by ECMA-335. This is in Mono and certain cases not the same
+as the one reported by Type.FullName (nested classes e.g.).
+
 The preserve attribute ensures that all the fields of the type Baz will be
 always be linked, not matter if they are used or not, but that neither the
 fields or the methods of Bar will be linked if they are not used. Not
index cca910f7cd83e12aafc2a7d833c3fca81eea2b20..3bf5e2463bbbb4d63119192232235aed33ed1daa 100644 (file)
@@ -2,6 +2,9 @@
   <Assemblies>
     <Assembly Name="DocTest" Version="0.0.0.0">
       <Attributes>
+        <Attribute>
+          <AttributeName>System.Diagnostics.Debuggable(System.Diagnostics.DebuggableAttribute+DebuggingModes.IgnoreSymbolStoreSequencePoints)</AttributeName>
+        </Attribute>
         <Attribute>
           <AttributeName>System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows=true)</AttributeName>
         </Attribute>
index c2ec0ea27f41cca6693452d08d47f9109d74d274..13ad1ddd850a3748071b16bdea2f889fe5845be6 100644 (file)
@@ -2,6 +2,9 @@
   <Assemblies>
     <Assembly Name="DocTest" Version="0.0.0.0">
       <Attributes>
+        <Attribute>
+          <AttributeName>System.Diagnostics.Debuggable(System.Diagnostics.DebuggableAttribute+DebuggingModes.IgnoreSymbolStoreSequencePoints)</AttributeName>
+        </Attribute>
         <Attribute>
           <AttributeName>System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows=true)</AttributeName>
         </Attribute>
index 365d685b38d3faa9e78837190fa254ed6c826bac..1d4f1666def111adb322537776cda56822efec8b 100644 (file)
@@ -2,6 +2,9 @@
   <Assemblies>
     <Assembly Name="DocTest" Version="0.0.0.0">
       <Attributes>
+        <Attribute>
+          <AttributeName>System.Diagnostics.Debuggable(System.Diagnostics.DebuggableAttribute+DebuggingModes.IgnoreSymbolStoreSequencePoints)</AttributeName>
+        </Attribute>
         <Attribute>
           <AttributeName>System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows=true)</AttributeName>
         </Attribute>
index 56d6aca288cf457480885f4b33c71f50dbd015b7..45914b3273ce4594a915a8309a110d9125e7db1f 100644 (file)
@@ -2,6 +2,9 @@
   <Assemblies>
     <Assembly Name="DocTest" Version="2.0.0.0">
       <Attributes>
+        <Attribute>
+          <AttributeName>System.Diagnostics.Debuggable(System.Diagnostics.DebuggableAttribute+DebuggingModes.IgnoreSymbolStoreSequencePoints)</AttributeName>
+        </Attribute>
         <Attribute>
           <AttributeName>System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows=true)</AttributeName>
         </Attribute>
index cca910f7cd83e12aafc2a7d833c3fca81eea2b20..3bf5e2463bbbb4d63119192232235aed33ed1daa 100644 (file)
@@ -2,6 +2,9 @@
   <Assemblies>
     <Assembly Name="DocTest" Version="0.0.0.0">
       <Attributes>
+        <Attribute>
+          <AttributeName>System.Diagnostics.Debuggable(System.Diagnostics.DebuggableAttribute+DebuggingModes.IgnoreSymbolStoreSequencePoints)</AttributeName>
+        </Attribute>
         <Attribute>
           <AttributeName>System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows=true)</AttributeName>
         </Attribute>
index 8f7e736ff6331b4c133145b5ff49e894967b4ad6..f13ce63d029438bedb9bb1c7ebd96c6530d93191 100755 (executable)
@@ -178,25 +178,9 @@ class MakeBundle {
                List<string> assemblies = LoadAssemblies (sources);
                List<string> files = new List<string> ();
                foreach (string file in assemblies)
-                       QueueAssembly (files, file);
+                       if (!QueueAssembly (files, file))
+                               return 1;
                        
-               // Special casing mscorlib.dll: any specified mscorlib.dll cannot be loaded
-               // by Assembly.ReflectionFromLoadFrom(). Instead the fx assembly which runs
-               // mkbundle.exe is loaded, which is not what we want.
-               // So, replace it with whatever actually specified.
-               foreach (string srcfile in sources) {
-                       if (Path.GetFileName (srcfile) == "mscorlib.dll") {
-                               foreach (string file in files) {
-                                       if (Path.GetFileName (new Uri (file).LocalPath) == "mscorlib.dll") {
-                                               files.Remove (file);
-                                               files.Add (new Uri (Path.GetFullPath (srcfile)).LocalPath);
-                                               break;
-                                       }
-                               }
-                               break;
-                       }
-               }
-
                GenerateBundles (files);
                //GenerateJitWrapper ();
                
@@ -568,27 +552,41 @@ void          mono_register_config_for_assembly (const char* assembly_name, cons
        }
        
        static readonly Universe universe = new Universe ();
+       static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
        
-       static void QueueAssembly (List<string> files, string codebase)
+       static bool QueueAssembly (List<string> files, string codebase)
        {
                // Console.WriteLine ("CODE BASE IS {0}", codebase);
                if (files.Contains (codebase))
-                       return;
+                       return true;
+
+               var path = new Uri(codebase).LocalPath;
+               var name = Path.GetFileName (path);
+               string found;
+               if (loaded_assemblies.TryGetValue (name, out found)) {
+                       Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
+                       return false;
+               }
+
+               loaded_assemblies.Add (name, path);
 
                files.Add (codebase);
                if (!autodeps)
-                       return;
+                       return true;
                try {
-                       Assembly a = universe.LoadFile (new Uri(codebase).LocalPath);
+                       Assembly a = universe.LoadFile (path);
 
                        foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
-                               a = universe.Load (an.Name);
-                               QueueAssembly (files, a.CodeBase);
+                               a = universe.Load (an.FullName);
+                               if (!QueueAssembly (files, a.CodeBase))
+                                       return false;
                        }
                } catch (Exception e) {
                        if (!skip_scan)
                                throw;
                }
+
+               return true;
        }
 
        static Assembly LoadAssembly (string assembly)
@@ -639,7 +637,7 @@ void          mono_register_config_for_assembly (const char* assembly_name, cons
 
        static void Error (string msg)
        {
-               Console.Error.WriteLine (msg);
+               Console.Error.WriteLine ("ERROR: " + msg);
                Environment.Exit (1);
        }
 
index 9bd32cf8c668555b06f920478ee15ee03b7a3f95..f40641c21f965af39738ddd53fad6067e24f632e 100644 (file)
@@ -1,5 +1,6 @@
 static MonoBundledAssembly **bundled;
 
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <zlib.h>
index 7f21b8c4dfb344b2f52d024035a7cc9090d7ba94..1104b1c1169c1f40da1c2cbc39d00e9424f5fa1b 100644 (file)
@@ -29,8 +29,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1
-
 using System;
 using System.Reflection;
 using System.Collections;
@@ -90,7 +88,9 @@ public class Outline {
                        OutlineParams (method.GetParameters ());
                        o.Write (")");
 
+#if NET_2_0
                        WriteGenericConstraints (t.GetGenericArguments ());
+#endif                 
        
                        o.WriteLine (";"); 
                        return;
@@ -119,9 +119,9 @@ public class Outline {
                        if (underlyingType != typeof (int))
                                o.Write (" : {0}", FormatType (underlyingType));
                }
-
+#if NET_2_0
                WriteGenericConstraints (t.GetGenericArguments ());
-
+#endif         
                o.WriteLine (" {");
                o.Indent++;
 
@@ -396,11 +396,15 @@ public class Outline {
                }
 
                o.Write (mi.Name);
+#if NET_2_0
                o.Write (FormatGenericParams (mi.GetGenericArguments ()));
+#endif
                o.Write (" (");
                OutlineParams (mi.GetParameters ());
                o.Write (")");
+#if NET_2_0
                WriteGenericConstraints (mi.GetGenericArguments ());
+#endif
                o.Write (";");
        }
        
@@ -559,6 +563,7 @@ public class Outline {
                 }
        }
 
+#if NET_2_0
        string FormatGenericParams (Type [] args)
        {
                StringBuilder sb = new StringBuilder ();
@@ -574,6 +579,7 @@ public class Outline {
                sb.Append (">");
                return sb.ToString ();
        }
+#endif
 
        // TODO: fine tune this so that our output is less verbose. We need to figure
        // out a way to do this while not making things confusing.
@@ -673,7 +679,9 @@ public class Outline {
        void GetTypeName (StringBuilder sb, Type t)
        {
                sb.Append (RemoveGenericArity (t.Name));
+#if NET_2_0
                sb.Append (FormatGenericParams (t.GetGenericArguments ()));
+#endif
        }
 
        string GetFullName (Type t)
@@ -685,10 +693,12 @@ public class Outline {
 
        void GetFullName_recursed (StringBuilder sb, Type t, bool recursed)
        {
+#if NET_2_0
                if (t.IsGenericParameter) {
                        sb.Append (t.Name);
                        return;
                }
+#endif
 
                if (t.DeclaringType != null) {
                        GetFullName_recursed (sb, t.DeclaringType, true);
@@ -706,6 +716,7 @@ public class Outline {
                GetTypeName (sb, t);
        }
 
+#if NET_2_0
        void WriteGenericConstraints (Type [] args)
        {
 
@@ -761,6 +772,7 @@ public class Outline {
                        }
                }
        }
+#endif
  
        string OperatorFromName (string name)
        {
@@ -1024,5 +1036,3 @@ public class Comparer : IComparer  {
        }
 }
 }
-
-#endif
\ No newline at end of file
index a21048644b874a752367abc71a40125a008acbf0..79eda999ee4dc2ba60fed8ff4a2d75011ebdb9dd 100644 (file)
@@ -33,9 +33,9 @@ namespace Mono.XBuild.CommandLine {
        public static class ErrorUtilities {
 
                static string[] version = {
-                       String.Format ("XBuild Engine Version {0}", Consts.MonoVersion),
+                       String.Format ("XBuild Engine Version {0}", XBuildConsts.Version),
                        String.Format ("Mono, Version {0}", Consts.MonoVersion),
-                       "Copyright (C) Marek Sieradzki 2005-2008, Novell 2008-2011.",
+                       "Copyright (C) 2005-2013 Various Mono authors",
                };
 
                
index 0fcbbfa7848437c7df95a0118da7c3b1fdae0907..8575340f90db6379a8256d9913113ee021af2810 100644 (file)
@@ -3,99 +3,86 @@ SUBDIRS =
 include ../../build/rules.make
 NO_TESTS = yes
 
-BUILD_FRAMEWORK = Microsoft.Build.Framework.dll
-BUILD_ENGINE = Microsoft.Build.Engine.dll
-INSTALL_FRAMEWORK_VERSION = $(FRAMEWORK_VERSION)
+include xbuild.make
 
-ifeq (3.5, $(FRAMEWORK_VERSION))
-NAME_SUFFIX = .v3.5
-ASSEMBLY_VERSION = 3.5.0.0
-BUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/$(BUILD_FRAMEWORK)
-BUILD_ENGINE := $(topdir)/class/lib/$(PROFILE)/$(BUILD_ENGINE)
-else
-ifeq (4, $(FRAMEWORK_VERSION_MAJOR))
-NAME_SUFFIX = .v4.0
-ASSEMBLY_VERSION = 4.0.0.0
-INSTALL_FRAMEWORK_VERSION = 4.0
-endif
-endif
-
-LOCAL_MCS_FLAGS = -r:$(BUILD_FRAMEWORK) -r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll -r:$(BUILD_ENGINE)
+LOCAL_MCS_FLAGS = -r:$(XBUILD_FRAMEWORK) -r:$(XBUILD_UTILITIES) -r:$(XBUILD_ENGINE)
 PROGRAM = xbuild.exe
 
 include ../../build/executable.make
 
 XBUILD_DIR=.
-XBUILD_FRAMEWORKS_DIR=$(mono_libdir)/mono/xbuild-frameworks/.NETFramework/
-REDISTLIST_DIR=$(XBUILD_FRAMEWORKS_DIR)/v$(FRAMEWORK_VERSION)/RedistList
-include $(XBUILD_DIR)/xbuild_targets.make
+include $(XBUILD_DIR)/xbuild_test.make
+
+ifeq (4.0, $(FRAMEWORK_VERSION))
+install-local: xbuild-net4-fail
+else
+install-local: install-extras
+endif
+
+NETFRAMEWORK_DIR=$(mono_libdir)/mono/xbuild-frameworks/.NETFramework
+VS_TARGETS_DIR = $(mono_libdir)/mono/xbuild/Microsoft/VisualStudio
+PORTABLE_TARGETS_DIR = $(mono_libdir)/mono/xbuild/Microsoft/Portable
+
+
+install-extras: install-bin-data install-frameworks install-pcl-targets install-web-targets
+
+install-bin-data:
+       $(MKINSTALLDIRS) $(DESTDIR)$(XBUILD_BIN_DIR)/MSBuild
+       $(INSTALL_DATA) data/xbuild.rsp $(DESTDIR)$(XBUILD_BIN_DIR)
+       $(INSTALL_DATA) data/$(XBUILD_VERSION)/Microsoft.Common.tasks $(DESTDIR)$(XBUILD_BIN_DIR)
+       $(INSTALL_DATA) data/$(XBUILD_VERSION)/Microsoft.Common.targets $(DESTDIR)$(XBUILD_BIN_DIR)
+       $(INSTALL_DATA) data/Microsoft.Build.xsd $(DESTDIR)$(XBUILD_BIN_DIR)
+       $(INSTALL_DATA) data/Microsoft.CSharp.targets $(DESTDIR)$(XBUILD_BIN_DIR)
+       $(INSTALL_DATA) data/Microsoft.VisualBasic.targets $(DESTDIR)$(XBUILD_BIN_DIR)
+       $(INSTALL_DATA) data/MSBuild/Microsoft.Build.CommonTypes.xsd $(DESTDIR)$(XBUILD_BIN_DIR)/MSBuild
+       $(INSTALL_DATA) data/MSBuild/Microsoft.Build.Core.xsd $(DESTDIR)$(XBUILD_BIN_DIR)/MSBuild
+       sed -e 's/@ASM_VERSION@/$(XBUILD_ASSEMBLY_VERSION)/g' data/xbuild.exe.config.in > $(DESTDIR)$(XBUILD_BIN_DIR)/xbuild.exe.config
+
+install-frameworks:
+       $(MKINSTALLDIRS) $(DESTDIR)$(NETFRAMEWORK_DIR)/v$(FRAMEWORK_VERSION)/RedistList
+       $(INSTALL_DATA) frameworks/net_$(FRAMEWORK_VERSION).xml $(DESTDIR)$(NETFRAMEWORK_DIR)/v$(FRAMEWORK_VERSION)/RedistList/FrameworkList.xml
+       $(MKINSTALLDIRS) $(DESTDIR)$(NETFRAMEWORK_DIR)/v3.0/RedistList
+       $(INSTALL_DATA) frameworks/net_3.0.xml $(DESTDIR)$(NETFRAMEWORK_DIR)/v3.0/RedistList/FrameworkList.xml
+       $(MKINSTALLDIRS) $(DESTDIR)$(NETFRAMEWORK_DIR)/v4.0/RedistList
+       $(INSTALL_DATA) frameworks/net_4.0.xml $(DESTDIR)$(NETFRAMEWORK_DIR)/v4.0/RedistList/FrameworkList.xml
+       $(MKINSTALLDIRS) $(DESTDIR)$(NETFRAMEWORK_DIR)/v4.0/Profile/Client/RedistList
+       $(INSTALL_DATA) frameworks/net_4.0_client.xml $(DESTDIR)$(NETFRAMEWORK_DIR)/v4.0/Profile/Client/RedistList/FrameworkList.xml
 
-install-local: install-extras
+install-pcl-targets:
+       $(MKINSTALLDIRS) $(DESTDIR)$(PORTABLE_TARGETS_DIR)/v4.0
+       $(INSTALL_DATA) targets/Microsoft.Portable.CSharp_4.0.targets $(DESTDIR)$(PORTABLE_TARGETS_DIR)/v4.0/Microsoft.Portable.CSharp.targets
+       $(MKINSTALLDIRS) $(DESTDIR)$(PORTABLE_TARGETS_DIR)/v4.5
+       $(INSTALL_DATA) targets/Microsoft.Portable.CSharp_4.5.targets $(DESTDIR)$(PORTABLE_TARGETS_DIR)/v4.5/Microsoft.Portable.CSharp.targets
 
-WEBAPP_DIR = Microsoft/VisualStudio
-SILVERLIGHT_DIR = $(mono_libdir)/mono/xbuild/Microsoft/Silverlight
-PORTABLE_DIR = $(mono_libdir)/mono/xbuild/Microsoft/Portable
-EXTRAS_DIR = $(mono_libdir)/mono/$(INSTALL_FRAMEWORK_VERSION)
-install-extras: 
-       $(MKINSTALLDIRS) $(DESTDIR)$(EXTRAS_DIR) $(DESTDIR)$(REDISTLIST_DIR) $(DESTDIR)$(XBUILD_FRAMEWORKS_DIR)/v3.0/RedistList $(DESTDIR)$(XBUILD_FRAMEWORKS_DIR)/v4.0/RedistList $(DESTDIR)$(mono_libdir)/mono/3.5 $(DESTDIR)$(mono_libdir)/mono/4.0
-       $(INSTALL_DATA) xbuild/xbuild.rsp $(DESTDIR)$(mono_libdir)/mono/$(FRAMEWORK_VERSION)
-       $(INSTALL_DATA) xbuild/$(INSTALL_FRAMEWORK_VERSION)/Microsoft.Common.tasks $(DESTDIR)$(EXTRAS_DIR)
-       $(INSTALL_DATA) xbuild/$(INSTALL_FRAMEWORK_VERSION)/Microsoft.Common.targets $(DESTDIR)$(EXTRAS_DIR)
-       $(INSTALL_DATA) xbuild/Microsoft.Build.xsd $(DESTDIR)$(EXTRAS_DIR)
-       $(INSTALL_DATA) xbuild/2.0/Microsoft.Common.targets $(DESTDIR)$(mono_libdir)/mono/2.0
-       $(INSTALL_DATA) xbuild/3.5/Microsoft.Common.targets $(DESTDIR)$(mono_libdir)/mono/3.5
-       $(INSTALL_DATA) xbuild/Microsoft.CSharp.targets $(DESTDIR)$(EXTRAS_DIR)
-       $(INSTALL_DATA) xbuild/Microsoft.VisualBasic.targets $(DESTDIR)$(EXTRAS_DIR)
-       $(INSTALL_DATA) xbuild/$(FRAMEWORK_VERSION)/FrameworkList.xml $(DESTDIR)$(REDISTLIST_DIR)
-       $(INSTALL_DATA) xbuild/4.0/FrameworkList.xml $(DESTDIR)$(XBUILD_FRAMEWORKS_DIR)/v4.0/RedistList/FrameworkList.xml
-       $(INSTALL_DATA) xbuild/FrameworkList-3.0.xml $(DESTDIR)$(XBUILD_FRAMEWORKS_DIR)/v3.0/RedistList/FrameworkList.xml
-       $(MKINSTALLDIRS) $(DESTDIR)$(EXTRAS_DIR)/MSBuild
-       $(INSTALL_DATA) xbuild/MSBuild/Microsoft.Build.CommonTypes.xsd $(DESTDIR)$(EXTRAS_DIR)/MSBuild
-       $(INSTALL_DATA) xbuild/MSBuild/Microsoft.Build.Core.xsd $(DESTDIR)$(EXTRAS_DIR)/MSBuild
-       $(MKINSTALLDIRS) $(DESTDIR)$(mono_libdir)/mono/xbuild
-       $(MKINSTALLDIRS) $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)/v9.0/WebApplications
-       $(INSTALL_DATA) xbuild/Microsoft.WebApplication.targets $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)/v9.0/WebApplications
-       $(MKINSTALLDIRS) $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)/v10.0/WebApplications
-       $(INSTALL_DATA) xbuild/Microsoft.WebApplication.targets $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)/v10.0/WebApplications
-       $(MKINSTALLDIRS) $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)/v11.0/WebApplications
-       $(INSTALL_DATA) xbuild/Microsoft.WebApplication.targets $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)/v11.0/WebApplications
-       $(MKINSTALLDIRS) $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0
-       $(MKINSTALLDIRS) $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0
-       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.CSharp.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0
-       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.CSharp.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0
-       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.VisualBasic.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0
-       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.VisualBasic.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0
-       sed -e 's/@SILVERLIGHT_VERSION@/2.0/g' xbuild/Microsoft.Silverlight.Common.targets > $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0/Microsoft.Silverlight.Common.targets
-       sed -e 's/@SILVERLIGHT_VERSION@/3.0/g' xbuild/Microsoft.Silverlight.Common.targets > $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0/Microsoft.Silverlight.Common.targets
-       $(MKINSTALLDIRS) $(DESTDIR)$(PORTABLE_DIR)/v4.0
-       $(MKINSTALLDIRS) $(DESTDIR)$(PORTABLE_DIR)/v4.5
-       $(INSTALL_DATA) xbuild/4.0/Microsoft.Portable.CSharp.targets $(DESTDIR)$(PORTABLE_DIR)/v4.0
-       $(INSTALL_DATA) xbuild/4.5/Microsoft.Portable.CSharp.targets $(DESTDIR)$(PORTABLE_DIR)/v4.5
-       $(INSTALL_DATA) xbuild/Microsoft.Portable.CSharp.targets $(DESTDIR)$(mono_libdir)/mono/4.0
+install-web-targets:
+       $(MKINSTALLDIRS) $(DESTDIR)$(VS_TARGETS_DIR)/v9.0/WebApplications
+       $(INSTALL_DATA) targets/Microsoft.WebApplication.targets $(DESTDIR)$(VS_TARGETS_DIR)/v9.0/WebApplications
+       $(MKINSTALLDIRS) $(DESTDIR)$(VS_TARGETS_DIR)/v10.0/WebApplications
+       $(INSTALL_DATA) targets/Microsoft.WebApplication.targets $(DESTDIR)$(VS_TARGETS_DIR)/v10.0/WebApplications
+       $(MKINSTALLDIRS) $(DESTDIR)$(VS_TARGETS_DIR)/v11.0/WebApplications
+       $(INSTALL_DATA) targets/Microsoft.WebApplication.targets $(DESTDIR)$(VS_TARGETS_DIR)/v11.0/WebApplications
 
 EXTRA_DISTFILES = \
-       xbuild/xbuild.rsp \
-       xbuild/2.0/Microsoft.Common.tasks \
-       xbuild/3.5/Microsoft.Common.tasks \
-       xbuild/4.0/Microsoft.Common.tasks \
-       xbuild/2.0/Microsoft.Common.targets \
-       xbuild/3.5/Microsoft.Common.targets \
-       xbuild/4.0/Microsoft.Common.targets \
-       xbuild/4.0/Microsoft.Portable.CSharp.targets \
-       xbuild/4.5/Microsoft.Portable.CSharp.targets \
-       xbuild/2.0/FrameworkList.xml \
-       xbuild/3.5/FrameworkList.xml \
-       xbuild/4.0/FrameworkList.xml \
-       xbuild/4.5/FrameworkList.xml \
-       xbuild/FrameworkList-3.0.xml \
-       xbuild/Microsoft.Build.xsd \
-       xbuild/Microsoft.CSharp.targets \
-       xbuild/MSBuild/Microsoft.Build.CommonTypes.xsd \
-       xbuild/MSBuild/Microsoft.Build.Core.xsd         \
-       xbuild/Microsoft.VisualBasic.targets \
-       xbuild/Microsoft.WebApplication.targets \
-       xbuild/Microsoft.Silverlight.Common.targets \
-       xbuild/Microsoft.Silverlight.CSharp.targets \
-       xbuild/Microsoft.Silverlight.VisualBasic.targets \
-       xbuild/Microsoft.Portable.CSharp.targets \
-       xbuild_targets.make
+       data/xbuild.rsp \
+       data/xbuild.exe.config.in \
+       data/Microsoft.Build.xsd \
+       data/2.0/Microsoft.Common.tasks \
+       data/3.5/Microsoft.Common.tasks \
+       data/4.0/Microsoft.Common.tasks \
+       data/2.0/Microsoft.Common.targets \
+       data/3.5/Microsoft.Common.targets \
+       data/4.0/Microsoft.Common.targets \
+       data/Microsoft.CSharp.targets \
+       data/MSBuild/Microsoft.Build.CommonTypes.xsd \
+       data/MSBuild/Microsoft.Build.Core.xsd \
+       frameworks/net_2.0.xml \
+       frameworks/net_3.0.xml \
+       frameworks/net_3.5.xml \
+       frameworks/net_4.0.xml \
+       frameworks/net_4.5.xml \
+       targets/Microsoft.Portable.CSharp_4.0.targets \
+       targets/Microsoft.Portable.CSharp_4.5.targets \
+       targets/Microsoft.VisualBasic.targets \
+       targets/Microsoft.WebApplication.targets \
+       targets/Microsoft.Portable.CSharp.targets \
+       xbuild_tests.make
index 15d6bb7ea4589cf180a7833bdc5d034962105208..92fd84e949d0ac102aa1e063853fa29e8318288c 100644 (file)
@@ -117,8 +117,16 @@ namespace Mono.XBuild.CommandLine {
                        AddGeneralSettings (file, p);
 
                        StreamReader reader = new StreamReader (file);
+
                        string slnVersion = GetSlnFileVersion (reader);
-                       if (slnVersion == "11.00" || slnVersion == "12.00")
+
+                       if (slnVersion == "12.00")
+#if XBUILD_12
+                               p.DefaultToolsVersion = "12.0";
+#else
+                               p.DefaultToolsVersion = "4.0";
+#endif
+                       else if (slnVersion == "11.00")
                                p.DefaultToolsVersion = "4.0";
                        else if (slnVersion == "10.00")
                                p.DefaultToolsVersion = "3.5";
diff --git a/mcs/tools/xbuild/XBuildConsts.cs b/mcs/tools/xbuild/XBuildConsts.cs
new file mode 100644 (file)
index 0000000..dec2502
--- /dev/null
@@ -0,0 +1,20 @@
+class XBuildConsts
+{
+#if XBUILD_12
+       public const string Version = "12.0";
+       public const string AssemblyVersion = "12.0.0.0";
+       public const string FileVersion     = "12.0.21005.1";
+#elif NET_4_0
+       public const string Version = "4.0";
+       public const string AssemblyVersion = Consts.FxVersion;
+       public const string FileVersion     = Consts.FxFileVersion;
+#elif NET_3_5
+       public const string Version = "3.5";
+       public const string AssemblyVersion = Consts.FxVersion;
+       public const string FileVersion     = Consts.FxFileVersion;
+#else
+       public const string Version = "2.0";
+       public const string AssemblyVersion = Consts.FxVersion;
+       public const string FileVersion     = Consts.FxFileVersion;
+#endif
+}
diff --git a/mcs/tools/xbuild/data/12.0/Microsoft.Common.targets b/mcs/tools/xbuild/data/12.0/Microsoft.Common.targets
new file mode 100644 (file)
index 0000000..a038573
--- /dev/null
@@ -0,0 +1,917 @@
+<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <PropertyGroup>
+               <ImportByWildcardBeforeMicrosoftCommonTargets Condition="'$(ImportByWildcardBeforeMicrosoftCommonTargets)' == ''">true</ImportByWildcardBeforeMicrosoftCommonTargets>
+               <ImportByWildcardAfterMicrosoftCommonTargets Condition="'$(ImportByWildcardAfterMicrosoftCommonTargets)' == ''">true</ImportByWildcardAfterMicrosoftCommonTargets>
+       </PropertyGroup>
+
+       <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportBefore\*"
+               Condition="'$(ImportByWildcardBeforeMicrosoftCommonTargets)' == 'true' and Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportBefore')"/>
+
+       <Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')"/>
+
+       <PropertyGroup>
+               <OutputType Condition="'$(OutputType)' == ''">Exe</OutputType>
+               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <AssemblyName Condition="'$(AssemblyName)' == ''">$(MSBuildProjectName)</AssemblyName>
+               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath>
+               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
+               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
+
+               <TargetFrameworkIdentifier Condition="'$(TargetFrameworkIdentifier)' == ''">.NETFramework</TargetFrameworkIdentifier>
+               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v4.0</TargetFrameworkVersion>
+
+               <TargetFrameworkMoniker Condition="'$(TargetFrameworkMoniker)' == '' and '$(TargetFrameworkProfile)' != ''">$(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion),Profile=$(TargetFrameworkProfile)</TargetFrameworkMoniker>
+               <TargetFrameworkMoniker Condition="'$(TargetFrameworkMoniker)' == ''">$(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion)</TargetFrameworkMoniker>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
+               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
+
+               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
+               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
+
+               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
+               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+
+               <AddAdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == ''">true</AddAdditionalExplicitAssemblyReferences>
+               <AdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == 'true' and '$(TargetFrameworkVersion)' != 'v2.0' and '$(TargetFrameworkVersion)' != 'v3.0'">System.Core;$(AdditionalExplicitAssemblyReferences)</AdditionalExplicitAssemblyReferences>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <SkipCopyUnchangedFiles Condition="'$(SkipCopyUnchangedFiles)' == ''">true</SkipCopyUnchangedFiles>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' != '' and !HasTrailingSlash('$(BaseIntermediateOutputPath)')">$(BaseIntermediateOutputPath)\</BaseIntermediateOutputPath>
+               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
+               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
+               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <IntermediateOutputPath Condition="'$(IntermediateOutputPath)' != '' and !HasTrailingSlash('$(IntermediateOutputPath)')">$(IntermediateOutputPath)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
+
+               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
+               <_OutDirItem Include="$(OutDir)"/>
+       </ItemGroup>
+
+       <PropertyGroup>
+               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
+               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
+               <TargetDir Condition=" '$(TargetDir)' == '' ">@(_OutDirItem->'%(FullPath)')</TargetDir>
+               <TargetPath Condition=" '$(TargetPath)' == '' ">@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
+               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets</MSBuildAllProjects>
+               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
+               <TargetingClr2Framework Condition="('$(TargetFrameworkIdentifier)' == '.NETFramework') and ('$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5')">true</TargetingClr2Framework>
+       </PropertyGroup>
+
+       <Target Name="_ValidateEssentialProperties">
+               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <!-- If OutDir is specified via the command line, then the earlier check
+                    to add a trailing slash won't have any affect, so error here. -->
+               <Error
+                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
+                       Text="OutDir property must end with a slash."/>
+       </Target>
+
+       <Target Name="PrepareForBuild">
+               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
+
+               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
+                    @(None) and @(Content) -->
+               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
+                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
+                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
+               </CreateItem>
+
+               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
+                       Condition="'$(AppConfig)' == ''">
+                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
+               </FindAppConfigFile>
+
+               <MakeDir
+                       Directories="$(OutDir);$(IntermediateOutputPath);@(DocFileItem->'%(RelativeDir)')"
+               />
+       </Target>
+
+       <PropertyGroup>
+               <GetFrameworkPathsDependsOn />
+       </PropertyGroup>
+       <Target Name="GetFrameworkPaths"
+               Condition="'$(TargetFrameworkIdentifier)' == '' or '$(TargetFrameworkIdentifier)' == '.NETFramework'"
+               DependsOnTargets="$(GetFrameworkPathsDependsOn)">
+               <GetFrameworkPath>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v4.5'"
+                               TaskParameter="FrameworkVersion45Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v4.0'"
+                               TaskParameter="FrameworkVersion40Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion35Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion30Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion20Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+               </GetFrameworkPath>
+               <CreateProperty Value="@(_CombinedTargetFrameworkDirectoriesItem)">
+                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
+               </CreateProperty>
+
+               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
+                       Condition="'$(TargetFrameworkVersion)' != 'v4.5' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
+       </Target>
+
+       <PropertyGroup>
+               <GetReferenceAssemblyPathsDependsOn />
+       </PropertyGroup>
+       <Target Name="GetReferenceAssemblyPaths" DependsOnTargets="$(GetReferenceAssemblyPathsDependsOn)">
+               <!-- in case of .NETFramework, $(TargetFrameworkDirectory) would have been set by
+               GetFrameworkPaths, if it hasn't been changed, then clear it, to avoid duplicates -->
+               <CreateProperty Value="" Condition="'@(_CombinedTargetFrameworkDirectoriesItem)' == '$(TargetFrameworkDirectory)'">
+                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
+               </CreateProperty>
+
+               <GetReferenceAssemblyPaths
+                       Condition="'$(TargetFrameworkMoniker)' != '' and '$(_TargetFrameworkDirectories)' == ''"
+                       TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
+                       RootPath="$(TargetFrameworkRootPath)">
+
+                       <Output TaskParameter="ReferenceAssemblyPaths" PropertyName="_TargetFrameworkDirectories"/>
+                       <Output TaskParameter="FullFrameworkReferenceAssemblyPaths" PropertyName="_FullFrameworkReferenceAssemblyPaths"/>
+                       <Output TaskParameter="TargetFrameworkMonikerDisplayName" PropertyName="TargetFrameworkMonikerDisplayName"/>
+               </GetReferenceAssemblyPaths>
+
+
+               <!-- Remove duplicates. -->
+               <ItemGroup>
+                       <_TargetFrameworkDirectories Include="$(_TargetFrameworkDirectories);$(TargetFrameworkDirectory)" KeepDuplicates="false" />
+               </ItemGroup>
+               <PropertyGroup>
+                       <TargetFrameworkDirectory>@(_TargetFrameworkDirectories)</TargetFrameworkDirectory>
+               </PropertyGroup>
+
+               <ItemGroup Condition="'$(ImplicitlyExpandDesignTimeFacades)' == 'true'">
+                       <DesignTimeFacadeDirectoryRoots Include="$(TargetFrameworkDirectory)" />
+                       <DesignTimeFacadeDirectories Include="%(DesignTimeFacadeDirectoryRoots.Identity)\Facades\" Condition="Exists('%(DesignTimeFacadeDirectoryRoots.Identity)\Facades\')" />
+                       <_DesignTimeFacadeAssemblies Include="%(DesignTimeFacadeDirectories.Identity)\*.dll"/>
+               </ItemGroup>
+
+               <PropertyGroup Condition="'@(DesignTimeFacadeDirectories)' != ''">
+                       <TargetFrameworkDirectory>$(TargetFrameworkDirectory);@(DesignTimeFacadeDirectories)</TargetFrameworkDirectory>
+               </PropertyGroup>
+
+       </Target>
+
+       <PropertyGroup>
+               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
+                       .exe;
+                       .dll
+               </AllowedReferenceAssemblyFileExtensions>
+
+               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
+                       .exe.mdb;
+                       .dll.mdb;
+                       .xml
+               </AllowedReferenceRelatedFileExtensions>
+
+               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
+                       {CandidateAssemblyFiles};
+                       $(ReferencePath);
+                       @(AdditionalReferencePath);
+                       {HintPathFromItem};
+                       {TargetFrameworkDirectory};
+                       {PkgConfig};
+                       {GAC};
+                       {RawFileName};
+                       $(OutDir)
+               </AssemblySearchPaths>
+
+               <ResolveReferencesDependsOn>
+                       BeforeResolveReferences;
+                       ResolveProjectReferences;
+                       ResolveAssemblyReferences;
+                       AfterResolveReferences
+               </ResolveReferencesDependsOn>
+
+               <ResolveAssemblyReferencesDependsOn>
+                       GetFrameworkPaths;
+                       GetReferenceAssemblyPaths;
+                       PrepareForBuild
+               </ResolveAssemblyReferencesDependsOn>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(TargetFrameworkMoniker)' != ''">
+               <TargetFrameworkMonikerAssemblyAttributesPath Condition="'$(TargetFrameworkMonikerAssemblyAttributesPath)' == ''">$(IntermediateOutputPath)$(TargetFrameworkMoniker).AssemblyAttribute$(DefaultLanguageSourceExtension)</TargetFrameworkMonikerAssemblyAttributesPath>
+               <GenerateTargetFrameworkAttribute Condition="'$(GenerateTargetFrameworkAttribute)' == '' and '$(TargetFrameworkMoniker)'
+       != '' and '$(TargetingClr2Framework)' != 'true'">true</GenerateTargetFrameworkAttribute>
+       </PropertyGroup>
+
+       <ItemGroup Condition="'$(GenerateTargetFrameworkAttribute)' == 'true'">
+               <FileWrites Include="$(TargetFrameworkMonikerAssemblyAttributesPath)" />
+       </ItemGroup>
+
+       <Target Name="GenerateTargetFrameworkMonikerAttribute"
+               DependsOnTargets="PrepareForBuild;GetReferenceAssemblyPaths"
+               Inputs="$(MSBuildToolsPath)\Microsoft.Common.targets"
+               Outputs="$(TargetFrameworkMonikerAssemblyAttributesPath)"
+               Condition="'$(GenerateTargetFrameworkAttribute)' == 'true'">
+
+               <WriteLinesToFile
+                       File="$(TargetFrameworkMonikerAssemblyAttributesPath)"
+                       Lines="$(TargetFrameworkMonikerAssemblyAttributeText)"
+                       Overwrite="true"
+                       ContinueOnError="true"
+                       Condition="'@(Compile)' != '' and '$(TargetFrameworkMonikerAssemblyAttributeText)' != ''"
+               />
+
+               <ItemGroup Condition="'@(Compile)' != '' and '$(TargetFrameworkMonikerAssemblyAttributeText)' != ''">
+                       <Compile Include="$(TargetFrameworkMonikerAssemblyAttributesPath)"/>
+               </ItemGroup>
+       </Target>
+
+       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
+
+       <Target Name="BeforeResolveReferences" />
+       <Target Name="AfterResolveReferences" />
+
+       <Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
+               <CreateItem Include="@(Reference)" Exclude="$(AdditionalExplicitAssemblyReferences)">
+                       <Output TaskParameter="Include" ItemName="_Reference"/>
+               </CreateItem>
+
+               <CreateItem Include="$(AdditionalExplicitAssemblyReferences)">
+                       <Output TaskParameter="Include" ItemName="_Reference"/>
+               </CreateItem>
+
+               <ResolveAssemblyReference
+                       Assemblies="@(_Reference)"
+                       AssemblyFiles="@(ChildProjectReferences)"
+                       SearchPaths="$(AssemblySearchPaths)"
+                       CandidateAssemblyFiles="@(Content);@(None)"
+                       TargetFrameworkDirectories="$(TargetFrameworkDirectory)"
+                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
+                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
+                       FindDependencies="true"
+                       FindSatellites="true"
+                       FindRelatedFiles="true"
+                       TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
+                       TargetFrameworkMonikerDisplayName="$(TargetFrameworkMonikerDisplayName)"
+                       TargetFrameworkVersion="$(TargetFrameworkVersion)"
+               >
+                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
+                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="ReferenceDependencyPaths"/>
+                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
+                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
+                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
+
+                       <!-- FIXME: backwards compatibility -->
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
+               </ResolveAssemblyReference>
+       </Target>
+
+       <Target
+               Name="AssignProjectConfiguration"
+               Condition="'@(ProjectReference)' != ''">
+
+               <!-- assign configs if building a solution file -->
+               <AssignProjectConfiguration
+                       ProjectReferences = "@(ProjectReference)"
+                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
+                       Condition="'$(BuildingSolutionFile)' == 'true'">
+
+                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
+               </AssignProjectConfiguration>
+
+               <!-- Else, just -->
+               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Split projects into 2 lists
+               ProjectReferenceWithConfigurationExistent: Projects existent on disk
+               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
+
+       <Target Name="SplitProjectReferencesByExistent"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
+                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
+                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+               </CreateItem>
+       </Target>
+
+       <Target
+               Name="ResolveProjectReferences"
+               DependsOnTargets="SplitProjectReferencesByExistent"
+       >
+               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
+                    been built, so just get the target paths -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetTargetPath"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <!-- Building a project directly, build the referenced the projects also -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
+                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
+       </Target>
+
+       <Target Name = "CopyFilesMarkedCopyLocal">
+               <Copy
+                       SourceFiles="@(ReferenceCopyLocalPaths)"
+                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWritesShareable"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
+               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
+                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
+               </CreateProperty>
+       </Target>
+
+       <PropertyGroup>
+               <BuildDependsOn>
+                       BuildOnlySettings;
+                       BeforeBuild;
+                       CoreBuild;
+                       AfterBuild
+               </BuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BuildOnlySettings"/>
+       <Target Name="BeforeBuild"/>
+       <Target Name="AfterBuild"/>
+
+       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
+
+       <PropertyGroup>
+               <CoreBuildDependsOn>
+                       PrepareForBuild;
+                       GetFrameworkPaths;
+                       GetReferenceAssemblyPaths;
+                       PreBuildEvent;
+                       ResolveReferences;
+                       CopyFilesMarkedCopyLocal;
+                       PrepareResources;
+                       Compile;
+                       PrepareForRun;
+                       DeployOutputFiles;
+                       _RecordCleanFile;
+                       PostBuildEvent
+               </CoreBuildDependsOn>
+       </PropertyGroup>
+
+       <Target
+               Name="CoreBuild"
+               DependsOnTargets="$(CoreBuildDependsOn)"
+               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
+
+               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
+                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
+
+               <OnError ExecuteTargets="_RecordCleanFile" />
+       </Target>
+
+       <PropertyGroup>
+               <CompileDependsOn>
+                       ResolveReferences;
+                       GenerateTargetFrameworkMonikerAttribute;
+                       BeforeCompile;
+                       _TimestampBeforeCompile;
+                       CoreCompile;
+                       _TimestampAfterCompile;
+                       AfterCompile
+               </CompileDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeCompile" />
+       <Target Name="AfterCompile" />
+
+       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareForRunDependsOn>
+                       DeployOutputFiles
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       AssignTargetPaths;
+                       SplitResourcesByCulture;
+                       CreateManifestResourceNames;
+                       CopyNonResxEmbeddedResources;
+                       GenerateResources;
+                       GenerateSatelliteAssemblies;
+                       CompileLicxFiles
+               </PrepareResourcesDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
+
+       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
+               <!-- Extract .licx files into @(LicxFiles) -->
+               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
+                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
+               </CreateItem>
+
+               <!-- Split *remaining* resource files into various groups.. -->
+               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
+                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
+                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
+               </AssignCulture>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
+       <Target Name = "CopyNonResxEmbeddedResources"
+               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
+
+               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
+               <Copy SourceFiles = "@(NonResxWithCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles = "@(NonResxWithNoCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name = "GenerateResources">
+               <GenerateResource
+                       Sources = "@(ResxWithNoCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithNoCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+
+               <GenerateResource
+                       Sources = "@(ResxWithCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+       </Target>
+
+       <Target Name="GenerateSatelliteAssemblies"
+               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
+
+               <AL
+                       Culture = "%(Culture)"
+                       DelaySign="$(DelaySign)"
+                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       ToolExe="$(AlToolExe)"
+                       ToolPath="$(AlToolPath)"
+                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
+               </AL>
+
+
+               <CreateItem
+                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
+                       AdditionalMetadata = "Culture=%(Culture)"
+                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
+                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
+               </CreateItem>
+       </Target>
+
+       <PropertyGroup>
+               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
+       </PropertyGroup>
+
+       <Target Name = "CompileLicxFiles"
+               Condition = "'@(LicxFiles)' != ''"
+               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
+               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
+               <LC
+                       Sources = "@(LicxFiles)"
+                       LicenseTarget = "$(TargetFileName)"
+                       OutputDirectory = "$(IntermediateOutputPath)"
+                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
+                       ReferencedAssemblies = "@(ReferencePath);@(ReferenceDependencyPaths)"
+                       ToolPath = "$(LCToolPath)"
+                       ToolExe = "$(LCToolExe)">
+
+                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
+                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
+               </LC>
+       </Target>
+
+       <!-- Assign target paths to files that will need to be copied along with the project -->
+       <Target Name = "AssignTargetPaths">
+               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
+               </AssignTargetPath>
+       </Target>
+
+       <Target Name="DeployOutputFiles"
+               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
+
+               <Copy
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(OutDir)"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)" >
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_CopyDeployFilesToOutputDirectory"
+               DependsOnTargets="GetCopyToOutputDirectoryItems;
+                       _CopyDeployFilesToOutputDirectoryAlways;
+                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
+
+       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
+               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
+               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <!-- Copy if newer -->
+       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
+               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+
+       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
+               Inputs="@(AppConfigWithTargetPath)"
+               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(AppConfigWithTargetPath)"
+                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
+
+       <Target Name="GetCopyToOutputDirectoryItems"
+               Outputs="@(AllItemsFullPathWithTargetPath)"
+               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
+
+               <!-- FIXME: handle .vcproj
+                    FIXME: Private ProjectReferences are honored only in 3.5
+               -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetCopyToOutputDirectoryItems"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
+               </MSBuild>
+
+               <!-- Process items from child project. The outputs need to have full path
+                    as they'll be used from other projects -->
+
+               <CreateItem
+                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
+                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+
+               </CreateItem>
+
+               <!-- Process _this_ project's items -->
+
+               <CreateItem
+                       Include="@(NoneWithTargetPath->'%(FullPath)')"
+                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(ContentWithTargetPath->'%(FullPath)')"
+                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
+                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Pre/Post BuildEvents -->
+       <PropertyGroup>
+               <PreBuildEventDependsOn />
+       </PropertyGroup>
+
+       <Target Name="PreBuildEvent"
+               Condition="'$(PreBuildEvent)' != ''"
+               DependsOnTargets="$(PreBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
+       </Target>
+
+       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
+
+               Default: OnBuildSuccess
+               OnBuildSuccess: Run after a successful build
+               OnOutputUpdated: Run only if the output assembly got updates
+               Always: Run always
+       -->
+       <PropertyGroup>
+               <PostBuildEventDependsOn />
+       </PropertyGroup>
+
+       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
+            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
+            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
+            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
+       <Target Name="PostBuildEvent"
+               Condition="'$(PostBuildEvent)' != '' and
+                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
+                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
+               DependsOnTargets="$(PostBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
+       </Target>
+
+       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
+       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
+               </CreateItem>
+       </Target>
+       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
+               </CreateItem>
+       </Target>
+
+       <!-- Rebuild -->
+       <PropertyGroup>
+               <RebuildDependsOn>
+                       BeforeRebuild;
+                       Clean;
+                       $(MSBuildProjectDefaultTargets);
+                       AfterRebuild;
+               </RebuildDependsOn>
+
+               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
+                       BeforeRebuild;
+                       Clean;
+                       Build;
+                       AfterRebuild;
+               </RebuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeRebuild" />
+       <Target Name="AfterRebuild" />
+
+       <Target Name="Rebuild"
+               DependsOnTargets="$(RebuildDependsOn)"
+               Outputs="$(TargetPath)"/>
+
+       <!-- Clean -->
+       <Target Name="_RecordCleanFile"
+               DependsOnTargets="_GetCompileOutputsForClean">
+
+               <!-- add to list of previous writes for this platform/config -->
+
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+
+               <!-- CopyLocal files: In case all the projects build to common output
+                    directory, then other projects might depend on some of these
+                    CopyLocal files, so delete only the ones under *this* project
+                    directory -->
+               <FindUnderPath Path="$(MSBuildProjectDirectory)" Files="@(FileWritesShareable)">
+                       <Output TaskParameter="InPath" ItemName="FileWrites"/>
+               </FindUnderPath>
+
+               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
+                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
+               </RemoveDuplicates>
+
+               <WriteLinesToFile
+                       File="$(IntermediateOutputPath)$(CleanFile)"
+                       Lines="@(CombinedFileWrites)"
+                       Overwrite="true"/>
+       </Target>
+
+       <PropertyGroup>
+               <CleanDependsOn>
+                       BeforeClean;
+                       CleanReferencedProjects;
+                       CoreClean;
+                       AfterClean
+               </CleanDependsOn>
+       </PropertyGroup>
+
+       <Target Name="_GetCompileOutputsForClean">
+               <!-- assembly and debug file in the *intermediate output path* -->
+               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Get the list of files written, for clean -->
+       <Target Name="_GetCleanFileWrites"
+               DependsOnTargets="_GetCompileOutputsForClean">
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+       </Target>
+
+       <Target Name="CleanReferencedProjects"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
+                    else we are building a project directly, from the command line, so
+                    clean the referenced projects -->
+               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="Clean"
+                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
+
+       </Target>
+
+       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
+
+       <!-- Override in project to run before/after clean tasks -->
+       <Target Name="BeforeClean" />
+       <Target Name="AfterClean" />
+
+       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
+               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
+
+               <!-- all previous files written for this platform/config have been deleted,
+                    we can safely remove the file list now -->
+               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
+       </Target>
+
+       <PropertyGroup>
+               <ImplicitlyExpandDesignTimeFacades>true</ImplicitlyExpandDesignTimeFacades>
+
+               <ResolveReferencesDependsOn>
+                       $(ResolveReferencesDependsOn);
+                       ImplicitlyExpandDesignTimeFacades
+               </ResolveReferencesDependsOn>
+
+               <ImplicitlyExpandDesignTimeFacadesDependsOn>
+                       $(ImplicitlyExpandDesignTimeFacadesDependsOn);
+                       GetReferenceAssemblyPaths
+               </ImplicitlyExpandDesignTimeFacadesDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ImplicitlyExpandDesignTimeFacades" Condition="'$(ImplicitlyExpandDesignTimeFacades)' == 'true'" DependsOnTargets="$(ImplicitlyExpandDesignTimeFacadesDependsOn)">
+
+               <PropertyGroup>
+                       <_HasReferenceToSystemRuntime Condition="'%(_ResolvedDependencyFiles.Filename)' == 'System.Runtime'">true</_HasReferenceToSystemRuntime>
+               </PropertyGroup>
+
+               <ItemGroup Condition="'$(_HasReferenceToSystemRuntime)' == 'true'">
+                       <!-- If the user has manually referenced these assemblies, remove them so we don't end up with duplicates -->
+                       <ReferencePath Remove="@(_DesignTimeFacadeAssemblies)"/>
+                       <ReferencePath Include="%(_DesignTimeFacadeAssemblies.Identity)">
+                               <WinMDFile>false</WinMDFile>
+                               <CopyLocal>false</CopyLocal>
+                               <ResolvedFrom>ImplicitlyExpandDesignTimeFacades</ResolvedFrom>
+                       </ReferencePath>
+                       <_ResolveAssemblyReferenceResolvedFiles Include="@(ReferencePath)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandDesignTimeFacades'" />
+               </ItemGroup>
+
+               <Message Importance="Low" Text="Including @(ReferencePath)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandDesignTimeFacades'" />
+
+       </Target>
+
+       <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportAfter\*"
+               Condition="'$(ImportByWildcardAfterMicrosoftCommonTargets)' == 'true' and Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportAfter')"/>
+</Project>
diff --git a/mcs/tools/xbuild/data/12.0/Microsoft.Common.tasks b/mcs/tools/xbuild/data/12.0/Microsoft.Common.tasks
new file mode 100644 (file)
index 0000000..550f6d0
--- /dev/null
@@ -0,0 +1,35 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateCSharpManifestResourceName"    AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetReferenceAssemblyPaths"   AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+</Project>
diff --git a/mcs/tools/xbuild/data/2.0/Microsoft.Common.targets b/mcs/tools/xbuild/data/2.0/Microsoft.Common.targets
new file mode 100644 (file)
index 0000000..fef6990
--- /dev/null
@@ -0,0 +1,771 @@
+<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+       <Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')"/>
+
+       <PropertyGroup>
+               <OutputType Condition="'$(OutputType)' == ''">Exe</OutputType>
+               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <AssemblyName Condition="'$(AssemblyName)' == ''">$(MSBuildProjectName)</AssemblyName>
+               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath>
+               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
+               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
+               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
+               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
+
+               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
+               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
+
+               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
+               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <SkipCopyUnchangedFiles Condition="'$(SkipCopyUnchangedFiles)' == ''">true</SkipCopyUnchangedFiles>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' != '' and !HasTrailingSlash('$(BaseIntermediateOutputPath)')">$(BaseIntermediateOutputPath)\</BaseIntermediateOutputPath>
+               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
+               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
+               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <IntermediateOutputPath Condition="'$(IntermediateOutputPath)' != '' and !HasTrailingSlash('$(IntermediateOutputPath)')">$(IntermediateOutputPath)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
+
+               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
+               <_OutDirItem Include="$(OutDir)"/>
+       </ItemGroup>
+
+       <PropertyGroup>
+               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
+               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
+               <TargetDir Condition=" '$(TargetDir)' == '' ">@(_OutDirItem->'%(FullPath)')</TargetDir>
+               <TargetPath Condition=" '$(TargetPath)' == '' ">@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
+               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets</MSBuildAllProjects>
+
+               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
+       </PropertyGroup>
+
+       <Target Name="_ValidateEssentialProperties">
+               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <!-- If OutDir is specified via the command line, then the earlier check
+                    to add a trailing slash won't have any affect, so error here. -->
+               <Error
+                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
+                       Text="OutDir property must end with a slash."/>
+       </Target>
+
+       <Target Name="PrepareForBuild">
+               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
+
+               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
+                    @(None) and @(Content) -->
+               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
+                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
+                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
+               </CreateItem>
+
+               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
+                       Condition="'$(AppConfig)' == ''">
+                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
+               </FindAppConfigFile>
+
+               <MakeDir
+                       Directories="$(OutDir);$(IntermediateOutputPath);@(DocFileItem->'%(RelativeDir)')"
+               />
+       </Target>
+
+       <PropertyGroup>
+               <GetFrameworkPathsDependsOn />
+       </PropertyGroup>
+       <Target Name="GetFrameworkPaths" DependsOnTargets="$(GetFrameworkPathsDependsOn)">
+               <GetFrameworkPath>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion35Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion30Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion20Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+               </GetFrameworkPath>
+               <CreateProperty Value="@(_CombinedTargetFrameworkDirectoriesItem)">
+                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
+               </CreateProperty>
+
+               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
+                       Condition="'$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
+       </Target>
+
+       <PropertyGroup>
+               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
+                       .exe;
+                       .dll
+               </AllowedReferenceAssemblyFileExtensions>
+
+               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
+                       .exe.mdb;
+                       .dll.mdb;
+                       .xml
+               </AllowedReferenceRelatedFileExtensions>
+
+               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
+                       {CandidateAssemblyFiles};
+                       $(ReferencePath);
+                       @(AdditionalReferencePath);
+                       {HintPathFromItem};
+                       {TargetFrameworkDirectory};
+                       {PkgConfig};
+                       {GAC};
+                       {RawFileName};
+                       $(OutDir)
+               </AssemblySearchPaths>
+
+               <ResolveReferencesDependsOn>
+                       BeforeResolveReferences;
+                       ResolveProjectReferences;
+                       ResolveAssemblyReferences;
+                       AfterResolveReferences
+               </ResolveReferencesDependsOn>
+
+               <ResolveAssemblyReferencesDependsOn>
+                       GetFrameworkPaths;
+                       PrepareForBuild
+               </ResolveAssemblyReferencesDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
+
+       <Target Name="BeforeResolveReferences" />
+       <Target Name="AfterResolveReferences" />
+
+       <Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
+               <ResolveAssemblyReference
+                       Assemblies="@(Reference)"
+                       AssemblyFiles="@(ChildProjectReferences)"
+                       SearchPaths="$(AssemblySearchPaths)"
+                       CandidateAssemblyFiles="@(Content);@(None)"
+                       TargetFrameworkDirectories="$(TargetFrameworkDirectory)"
+                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
+                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
+                       FindDependencies="true"
+                       FindSatellites="true"
+                       FindRelatedFiles="true"
+               >
+                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
+                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
+                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
+                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
+                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
+               </ResolveAssemblyReference>
+       </Target>
+
+       <Target
+               Name="AssignProjectConfiguration"
+               Condition="'@(ProjectReference)' != ''">
+
+               <!-- assign configs if building a solution file -->
+               <AssignProjectConfiguration
+                       ProjectReferences = "@(ProjectReference)"
+                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
+                       Condition="'$(BuildingSolutionFile)' == 'true'">
+
+                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
+               </AssignProjectConfiguration>
+
+               <!-- Else, just -->
+               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Split projects into 2 lists
+               ProjectReferenceWithConfigurationExistent: Projects existent on disk
+               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
+
+       <Target Name="SplitProjectReferencesByExistent"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
+                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
+                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+               </CreateItem>
+       </Target>
+
+       <Target
+               Name="ResolveProjectReferences"
+               DependsOnTargets="SplitProjectReferencesByExistent"
+       >
+               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
+                    been built, so just get the target paths -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetTargetPath"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <!-- Building a project directly, build the referenced the projects also -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
+                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
+       </Target>
+
+       <Target Name = "CopyFilesMarkedCopyLocal">
+               <Copy
+                       SourceFiles="@(ReferenceCopyLocalPaths)"
+                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWritesShareable"/>
+               </Copy>
+       </Target>
+
+<!--
+       Not needed at the moment
+       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
+               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
+                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
+               </CreateProperty>
+       </Target>
+-->
+
+       <PropertyGroup>
+               <BuildDependsOn>
+                       BeforeBuild;
+                       CoreBuild;
+                       AfterBuild
+               </BuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeBuild"/>
+       <Target Name="AfterBuild"/>
+
+       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
+
+       <PropertyGroup>
+               <CoreBuildDependsOn>
+                       PrepareForBuild;
+                       GetFrameworkPaths;
+                       PreBuildEvent;
+                       ResolveReferences;
+                       CopyFilesMarkedCopyLocal;
+                       PrepareResources;
+                       Compile;
+                       PrepareForRun;
+                       DeployOutputFiles;
+                       _RecordCleanFile;
+                       PostBuildEvent
+               </CoreBuildDependsOn>
+       </PropertyGroup>
+
+       <Target
+               Name="CoreBuild"
+               DependsOnTargets="$(CoreBuildDependsOn)"
+               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
+
+               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
+                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
+
+               <OnError ExecuteTargets="_RecordCleanFile" />
+       </Target>
+
+       <PropertyGroup>
+               <CompileDependsOn>
+                       ResolveReferences;
+                       BeforeCompile;
+                       _TimestampBeforeCompile;
+                       CoreCompile;
+                       _TimestampAfterCompile;
+                       AfterCompile
+               </CompileDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeCompile" />
+       <Target Name="AfterCompile" />
+
+       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareForRunDependsOn>
+                       DeployOutputFiles
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       AssignTargetPaths;
+                       SplitResourcesByCulture;
+                       CreateManifestResourceNames;
+                       CopyNonResxEmbeddedResources;
+                       GenerateResources;
+                       GenerateSatelliteAssemblies;
+                       CompileLicxFiles
+               </PrepareResourcesDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
+
+       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
+               <!-- Extract .licx files into @(LicxFiles) -->
+               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
+                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
+               </CreateItem>
+
+               <!-- Split *remaining* resource files into various groups.. -->
+               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
+                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
+                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
+               </AssignCulture>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
+       <Target Name = "CopyNonResxEmbeddedResources"
+               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
+
+               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
+               <Copy SourceFiles = "@(NonResxWithCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles = "@(NonResxWithNoCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name = "GenerateResources">
+               <GenerateResource
+                       Sources = "@(ResxWithNoCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithNoCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+
+               <GenerateResource
+                       Sources = "@(ResxWithCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+       </Target>
+
+       <Target Name="GenerateSatelliteAssemblies"
+               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
+
+               <AL
+                       Culture = "%(Culture)"
+                       DelaySign="$(DelaySign)"
+                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       ToolExe="$(AlToolExe)"
+                       ToolPath="$(AlToolPath)"
+                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
+               </AL>
+
+
+               <CreateItem
+                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
+                       AdditionalMetadata = "Culture=%(Culture)"
+                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
+                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
+               </CreateItem>
+       </Target>
+
+       <PropertyGroup>
+               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
+       </PropertyGroup>
+
+       <Target Name = "CompileLicxFiles"
+               Condition = "'@(LicxFiles)' != ''"
+               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
+               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
+               <LC
+                       Sources = "@(LicxFiles)"
+                       LicenseTarget = "$(TargetFileName)"
+                       OutputDirectory = "$(IntermediateOutputPath)"
+                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
+                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
+                       ToolPath = "$(LCToolPath)"
+                       ToolExe = "$(LCToolExe)">
+
+                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
+                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
+               </LC>
+       </Target>
+
+       <!-- Assign target paths to files that will need to be copied along with the project -->
+       <Target Name = "AssignTargetPaths">
+               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
+               </AssignTargetPath>
+       </Target>
+
+       <Target Name="DeployOutputFiles"
+               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
+
+               <Copy
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(OutDir)"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)" >
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_CopyDeployFilesToOutputDirectory"
+               DependsOnTargets="GetCopyToOutputDirectoryItems;
+                       _CopyDeployFilesToOutputDirectoryAlways;
+                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
+
+       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
+               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
+               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <!-- Copy if newer -->
+       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
+               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+
+       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
+               Inputs="@(AppConfigWithTargetPath)"
+               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(AppConfigWithTargetPath)"
+                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
+
+       <Target Name="GetCopyToOutputDirectoryItems"
+               Outputs="@(AllItemsFullPathWithTargetPath)"
+               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
+
+               <!-- FIXME: handle .vcproj
+                    FIXME: Private ProjectReferences are honored only in 3.5
+               -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetCopyToOutputDirectoryItems"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
+               </MSBuild>
+
+               <!-- Process items from child project. The outputs need to have full path
+                    as they'll be used from other projects -->
+
+               <CreateItem
+                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
+                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+
+               </CreateItem>
+
+               <!-- Process _this_ project's items -->
+
+               <CreateItem
+                       Include="@(NoneWithTargetPath->'%(FullPath)')"
+                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(ContentWithTargetPath->'%(FullPath)')"
+                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
+                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Pre/Post BuildEvents -->
+       <PropertyGroup>
+               <PreBuildEventDependsOn />
+       </PropertyGroup>
+
+       <Target Name="PreBuildEvent"
+               Condition="'$(PreBuildEvent)' != ''"
+               DependsOnTargets="$(PreBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
+       </Target>
+
+       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
+
+               Default: OnBuildSuccess
+               OnBuildSuccess: Run after a successful build
+               OnOutputUpdated: Run only if the output assembly got updates
+               Always: Run always
+       -->
+       <PropertyGroup>
+               <PostBuildEventDependsOn />
+       </PropertyGroup>
+
+       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
+            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
+            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
+            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
+       <Target Name="PostBuildEvent"
+               Condition="'$(PostBuildEvent)' != '' and
+                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
+                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
+               DependsOnTargets="$(PostBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
+       </Target>
+
+       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
+       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
+               </CreateItem>
+       </Target>
+       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
+               </CreateItem>
+       </Target>
+
+       <!-- Rebuild -->
+       <PropertyGroup>
+               <RebuildDependsOn>
+                       BeforeRebuild;
+                       Clean;
+                       $(MSBuildProjectDefaultTargets);
+                       AfterRebuild;
+               </RebuildDependsOn>
+
+               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
+                       BeforeRebuild;
+                       Clean;
+                       Build;
+                       AfterRebuild;
+               </RebuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeRebuild" />
+       <Target Name="AfterRebuild" />
+
+       <Target Name="Rebuild"
+               DependsOnTargets="$(RebuildDependsOn)"
+               Outputs="$(TargetPath)"/>
+
+       <!-- Clean -->
+       <Target Name="_RecordCleanFile"
+               DependsOnTargets="_GetCompileOutputsForClean">
+
+               <!-- add to list of previous writes for this platform/config -->
+
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+
+               <!-- CopyLocal files: In case all the projects build to common output
+                    directory, then other projects might depend on some of these
+                    CopyLocal files, so delete only the ones under *this* project
+                    directory -->
+               <FindUnderPath Path="$(MSBuildProjectDirectory)" Files="@(FileWritesShareable)">
+                       <Output TaskParameter="InPath" ItemName="FileWrites"/>
+               </FindUnderPath>
+
+               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
+                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
+               </RemoveDuplicates>
+
+               <WriteLinesToFile
+                       File="$(IntermediateOutputPath)$(CleanFile)"
+                       Lines="@(CombinedFileWrites)"
+                       Overwrite="true"/>
+       </Target>
+
+       <PropertyGroup>
+               <CleanDependsOn>
+                       BeforeClean;
+                       CleanReferencedProjects;
+                       CoreClean;
+                       AfterClean
+               </CleanDependsOn>
+       </PropertyGroup>
+
+       <Target Name="_GetCompileOutputsForClean">
+               <!-- assembly and debug file in the *intermediate output path* -->
+               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Get the list of files written, for clean -->
+       <Target Name="_GetCleanFileWrites"
+               DependsOnTargets="_GetCompileOutputsForClean">
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+       </Target>
+
+       <Target Name="CleanReferencedProjects"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
+                    else we are building a project directly, from the command line, so
+                    clean the referenced projects -->
+               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="Clean"
+                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
+
+       </Target>
+
+       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
+
+       <!-- Override in project to run before/after clean tasks -->
+       <Target Name="BeforeClean" />
+       <Target Name="AfterClean" />
+
+       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
+               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
+
+               <!-- all previous files written for this platform/config have been deleted,
+                    we can safely remove the file list now -->
+               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
+       </Target>
+
+</Project>
diff --git a/mcs/tools/xbuild/data/2.0/Microsoft.Common.tasks b/mcs/tools/xbuild/data/2.0/Microsoft.Common.tasks
new file mode 100644 (file)
index 0000000..d1677c9
--- /dev/null
@@ -0,0 +1,34 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateCSharpManifestResourceName"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+</Project>
diff --git a/mcs/tools/xbuild/data/3.5/Microsoft.Common.targets b/mcs/tools/xbuild/data/3.5/Microsoft.Common.targets
new file mode 100644 (file)
index 0000000..03935bd
--- /dev/null
@@ -0,0 +1,778 @@
+<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+       <Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')"/>
+
+       <PropertyGroup>
+               <OutputType Condition="'$(OutputType)' == ''">Exe</OutputType>
+               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <AssemblyName Condition="'$(AssemblyName)' == ''">$(MSBuildProjectName)</AssemblyName>
+               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath>
+               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
+               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
+               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
+               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
+
+               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
+               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
+
+               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
+               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <SkipCopyUnchangedFiles Condition="'$(SkipCopyUnchangedFiles)' == ''">true</SkipCopyUnchangedFiles>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' != '' and !HasTrailingSlash('$(BaseIntermediateOutputPath)')">$(BaseIntermediateOutputPath)\</BaseIntermediateOutputPath>
+               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
+               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
+               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <IntermediateOutputPath Condition="'$(IntermediateOutputPath)' != '' and !HasTrailingSlash('$(IntermediateOutputPath)')">$(IntermediateOutputPath)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
+
+               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
+               <_OutDirItem Include="$(OutDir)"/>
+       </ItemGroup>
+
+       <PropertyGroup>
+               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
+               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
+               <TargetDir Condition=" '$(TargetDir)' == '' ">@(_OutDirItem->'%(FullPath)')</TargetDir>
+               <TargetPath Condition=" '$(TargetPath)' == '' ">@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
+               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets</MSBuildAllProjects>
+
+               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
+       </PropertyGroup>
+
+       <Target Name="_ValidateEssentialProperties">
+               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <!-- If OutDir is specified via the command line, then the earlier check
+                    to add a trailing slash won't have any affect, so error here. -->
+               <Error
+                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
+                       Text="OutDir property must end with a slash."/>
+       </Target>
+
+       <Target Name="PrepareForBuild">
+               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
+
+               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
+                    @(None) and @(Content) -->
+               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
+                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
+                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
+               </CreateItem>
+
+               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
+                       Condition="'$(AppConfig)' == ''">
+                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
+               </FindAppConfigFile>
+
+               <MakeDir
+                       Directories="$(OutDir);$(IntermediateOutputPath);@(DocFileItem->'%(RelativeDir)')"
+               />
+       </Target>
+
+       <PropertyGroup>
+               <GetFrameworkPathsDependsOn />
+       </PropertyGroup>
+       <Target Name="GetFrameworkPaths" DependsOnTargets="$(GetFrameworkPathsDependsOn)">
+               <GetFrameworkPath>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion35Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion30Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion20Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+               </GetFrameworkPath>
+               <CreateProperty Value="@(_CombinedTargetFrameworkDirectoriesItem)">
+                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
+               </CreateProperty>
+
+               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
+                       Condition="'$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
+       </Target>
+
+       <PropertyGroup>
+               <GetReferenceAssemblyPathsDependsOn />
+       </PropertyGroup>
+       <!-- Multi-targeting against "framework packs" is not supported with ToolsVersion < 4.0,
+            this target is just a place holder, can be overridden -->
+       <Target Name="GetReferenceAssemblyPaths" DependsOnTargets="$(GetReferenceAssemblyPathsDependsOn)" />
+
+       <PropertyGroup>
+               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
+                       .exe;
+                       .dll
+               </AllowedReferenceAssemblyFileExtensions>
+
+               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
+                       .exe.mdb;
+                       .dll.mdb;
+                       .xml
+               </AllowedReferenceRelatedFileExtensions>
+
+               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
+                       {CandidateAssemblyFiles};
+                       $(ReferencePath);
+                       @(AdditionalReferencePath);
+                       {HintPathFromItem};
+                       {TargetFrameworkDirectory};
+                       {PkgConfig};
+                       {GAC};
+                       {RawFileName};
+                       $(OutDir)
+               </AssemblySearchPaths>
+
+               <ResolveReferencesDependsOn>
+                       BeforeResolveReferences;
+                       ResolveProjectReferences;
+                       ResolveAssemblyReferences;
+                       AfterResolveReferences
+               </ResolveReferencesDependsOn>
+
+               <ResolveAssemblyReferencesDependsOn>
+                       GetFrameworkPaths;
+                       GetReferenceAssemblyPaths;
+                       PrepareForBuild
+               </ResolveAssemblyReferencesDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
+
+       <Target Name="BeforeResolveReferences" />
+       <Target Name="AfterResolveReferences" />
+
+       <Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
+               <ResolveAssemblyReference
+                       Assemblies="@(Reference)"
+                       AssemblyFiles="@(ChildProjectReferences)"
+                       SearchPaths="$(AssemblySearchPaths)"
+                       CandidateAssemblyFiles="@(Content);@(None)"
+                       TargetFrameworkDirectories="$(TargetFrameworkDirectory)"
+                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
+                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
+                       FindDependencies="true"
+                       FindSatellites="true"
+                       FindRelatedFiles="true"
+                       TargetFrameworkVersion="$(TargetFrameworkVersion)"
+               >
+                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
+                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
+                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
+                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
+                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
+               </ResolveAssemblyReference>
+       </Target>
+
+       <Target
+               Name="AssignProjectConfiguration"
+               Condition="'@(ProjectReference)' != ''">
+
+               <!-- assign configs if building a solution file -->
+               <AssignProjectConfiguration
+                       ProjectReferences = "@(ProjectReference)"
+                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
+                       Condition="'$(BuildingSolutionFile)' == 'true'">
+
+                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
+               </AssignProjectConfiguration>
+
+               <!-- Else, just -->
+               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Split projects into 2 lists
+               ProjectReferenceWithConfigurationExistent: Projects existent on disk
+               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
+
+       <Target Name="SplitProjectReferencesByExistent"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
+                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
+                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+               </CreateItem>
+       </Target>
+
+       <Target
+               Name="ResolveProjectReferences"
+               DependsOnTargets="SplitProjectReferencesByExistent"
+       >
+               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
+                    been built, so just get the target paths -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetTargetPath"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <!-- Building a project directly, build the referenced the projects also -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
+                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
+       </Target>
+
+       <Target Name = "CopyFilesMarkedCopyLocal">
+               <Copy
+                       SourceFiles="@(ReferenceCopyLocalPaths)"
+                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWritesShareable"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
+               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
+                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
+               </CreateProperty>
+       </Target>
+
+       <PropertyGroup>
+               <BuildDependsOn>
+                       BeforeBuild;
+                       CoreBuild;
+                       AfterBuild
+               </BuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeBuild"/>
+       <Target Name="AfterBuild"/>
+
+       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
+
+       <PropertyGroup>
+               <CoreBuildDependsOn>
+                       PrepareForBuild;
+                       GetFrameworkPaths;
+                       GetReferenceAssemblyPaths;
+                       PreBuildEvent;
+                       ResolveReferences;
+                       CopyFilesMarkedCopyLocal;
+                       PrepareResources;
+                       Compile;
+                       PrepareForRun;
+                       DeployOutputFiles;
+                       _RecordCleanFile;
+                       PostBuildEvent
+               </CoreBuildDependsOn>
+       </PropertyGroup>
+
+       <Target
+               Name="CoreBuild"
+               DependsOnTargets="$(CoreBuildDependsOn)"
+               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
+
+               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
+                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
+
+               <OnError ExecuteTargets="_RecordCleanFile" />
+       </Target>
+
+       <PropertyGroup>
+               <CompileDependsOn>
+                       ResolveReferences;
+                       BeforeCompile;
+                       _TimestampBeforeCompile;
+                       CoreCompile;
+                       _TimestampAfterCompile;
+                       AfterCompile
+               </CompileDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeCompile" />
+       <Target Name="AfterCompile" />
+
+       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareForRunDependsOn>
+                       DeployOutputFiles
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       AssignTargetPaths;
+                       SplitResourcesByCulture;
+                       CreateManifestResourceNames;
+                       CopyNonResxEmbeddedResources;
+                       GenerateResources;
+                       GenerateSatelliteAssemblies;
+                       CompileLicxFiles
+               </PrepareResourcesDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
+
+       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
+               <!-- Extract .licx files into @(LicxFiles) -->
+               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
+                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
+               </CreateItem>
+
+               <!-- Split *remaining* resource files into various groups.. -->
+               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
+                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
+                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
+               </AssignCulture>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
+       <Target Name = "CopyNonResxEmbeddedResources"
+               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
+
+               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
+               <Copy SourceFiles = "@(NonResxWithCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles = "@(NonResxWithNoCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name = "GenerateResources">
+               <GenerateResource
+                       Sources = "@(ResxWithNoCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithNoCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+
+               <GenerateResource
+                       Sources = "@(ResxWithCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+       </Target>
+
+       <Target Name="GenerateSatelliteAssemblies"
+               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
+
+               <AL
+                       Culture = "%(Culture)"
+                       DelaySign="$(DelaySign)"
+                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       ToolExe="$(AlToolExe)"
+                       ToolPath="$(AlToolPath)"
+                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
+               </AL>
+
+
+               <CreateItem
+                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
+                       AdditionalMetadata = "Culture=%(Culture)"
+                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
+                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
+               </CreateItem>
+       </Target>
+
+       <PropertyGroup>
+               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
+       </PropertyGroup>
+
+       <Target Name = "CompileLicxFiles"
+               Condition = "'@(LicxFiles)' != ''"
+               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
+               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
+               <LC
+                       Sources = "@(LicxFiles)"
+                       LicenseTarget = "$(TargetFileName)"
+                       OutputDirectory = "$(IntermediateOutputPath)"
+                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
+                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
+                       ToolPath = "$(LCToolPath)"
+                       ToolExe = "$(LCToolExe)">
+
+                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
+                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
+               </LC>
+       </Target>
+
+       <!-- Assign target paths to files that will need to be copied along with the project -->
+       <Target Name = "AssignTargetPaths">
+               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
+               </AssignTargetPath>
+       </Target>
+
+       <Target Name="DeployOutputFiles"
+               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
+
+               <Copy
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(OutDir)"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)" >
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_CopyDeployFilesToOutputDirectory"
+               DependsOnTargets="GetCopyToOutputDirectoryItems;
+                       _CopyDeployFilesToOutputDirectoryAlways;
+                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
+
+       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
+               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
+               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <!-- Copy if newer -->
+       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
+               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+
+       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
+               Inputs="@(AppConfigWithTargetPath)"
+               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(AppConfigWithTargetPath)"
+                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
+
+       <Target Name="GetCopyToOutputDirectoryItems"
+               Outputs="@(AllItemsFullPathWithTargetPath)"
+               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
+
+               <!-- FIXME: handle .vcproj
+                    FIXME: Private ProjectReferences are honored only in 3.5
+               -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetCopyToOutputDirectoryItems"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
+               </MSBuild>
+
+               <!-- Process items from child project. The outputs need to have full path
+                    as they'll be used from other projects -->
+
+               <CreateItem
+                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
+                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+
+               </CreateItem>
+
+               <!-- Process _this_ project's items -->
+
+               <CreateItem
+                       Include="@(NoneWithTargetPath->'%(FullPath)')"
+                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(ContentWithTargetPath->'%(FullPath)')"
+                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
+                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Pre/Post BuildEvents -->
+       <PropertyGroup>
+               <PreBuildEventDependsOn />
+       </PropertyGroup>
+
+       <Target Name="PreBuildEvent"
+               Condition="'$(PreBuildEvent)' != ''"
+               DependsOnTargets="$(PreBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
+       </Target>
+
+       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
+
+               Default: OnBuildSuccess
+               OnBuildSuccess: Run after a successful build
+               OnOutputUpdated: Run only if the output assembly got updates
+               Always: Run always
+       -->
+       <PropertyGroup>
+               <PostBuildEventDependsOn />
+       </PropertyGroup>
+
+       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
+            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
+            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
+            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
+       <Target Name="PostBuildEvent"
+               Condition="'$(PostBuildEvent)' != '' and
+                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
+                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
+               DependsOnTargets="$(PostBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
+       </Target>
+
+       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
+       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
+               </CreateItem>
+       </Target>
+       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
+               </CreateItem>
+       </Target>
+
+       <!-- Rebuild -->
+       <PropertyGroup>
+               <RebuildDependsOn>
+                       BeforeRebuild;
+                       Clean;
+                       $(MSBuildProjectDefaultTargets);
+                       AfterRebuild;
+               </RebuildDependsOn>
+
+               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
+                       BeforeRebuild;
+                       Clean;
+                       Build;
+                       AfterRebuild;
+               </RebuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeRebuild" />
+       <Target Name="AfterRebuild" />
+
+       <Target Name="Rebuild"
+               DependsOnTargets="$(RebuildDependsOn)"
+               Outputs="$(TargetPath)"/>
+
+       <!-- Clean -->
+       <Target Name="_RecordCleanFile"
+               DependsOnTargets="_GetCompileOutputsForClean">
+
+               <!-- add to list of previous writes for this platform/config -->
+
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+
+               <!-- CopyLocal files: In case all the projects build to common output
+                    directory, then other projects might depend on some of these
+                    CopyLocal files, so delete only the ones under *this* project
+                    directory -->
+               <FindUnderPath Path="$(MSBuildProjectDirectory)" Files="@(FileWritesShareable)">
+                       <Output TaskParameter="InPath" ItemName="FileWrites"/>
+               </FindUnderPath>
+
+               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
+                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
+               </RemoveDuplicates>
+
+               <WriteLinesToFile
+                       File="$(IntermediateOutputPath)$(CleanFile)"
+                       Lines="@(CombinedFileWrites)"
+                       Overwrite="true"/>
+       </Target>
+
+       <PropertyGroup>
+               <CleanDependsOn>
+                       BeforeClean;
+                       CleanReferencedProjects;
+                       CoreClean;
+                       AfterClean
+               </CleanDependsOn>
+       </PropertyGroup>
+
+       <Target Name="_GetCompileOutputsForClean">
+               <!-- assembly and debug file in the *intermediate output path* -->
+               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Get the list of files written, for clean -->
+       <Target Name="_GetCleanFileWrites"
+               DependsOnTargets="_GetCompileOutputsForClean">
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+       </Target>
+
+       <Target Name="CleanReferencedProjects"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
+                    else we are building a project directly, from the command line, so
+                    clean the referenced projects -->
+               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="Clean"
+                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
+
+       </Target>
+
+       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
+
+       <!-- Override in project to run before/after clean tasks -->
+       <Target Name="BeforeClean" />
+       <Target Name="AfterClean" />
+
+       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
+               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
+
+               <!-- all previous files written for this platform/config have been deleted,
+                    we can safely remove the file list now -->
+               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
+       </Target>
+
+</Project>
diff --git a/mcs/tools/xbuild/data/3.5/Microsoft.Common.tasks b/mcs/tools/xbuild/data/3.5/Microsoft.Common.tasks
new file mode 100644 (file)
index 0000000..397d68c
--- /dev/null
@@ -0,0 +1,34 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateCSharpManifestResourceName"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+</Project>
diff --git a/mcs/tools/xbuild/data/4.0/Microsoft.Common.targets b/mcs/tools/xbuild/data/4.0/Microsoft.Common.targets
new file mode 100644 (file)
index 0000000..a038573
--- /dev/null
@@ -0,0 +1,917 @@
+<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <PropertyGroup>
+               <ImportByWildcardBeforeMicrosoftCommonTargets Condition="'$(ImportByWildcardBeforeMicrosoftCommonTargets)' == ''">true</ImportByWildcardBeforeMicrosoftCommonTargets>
+               <ImportByWildcardAfterMicrosoftCommonTargets Condition="'$(ImportByWildcardAfterMicrosoftCommonTargets)' == ''">true</ImportByWildcardAfterMicrosoftCommonTargets>
+       </PropertyGroup>
+
+       <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportBefore\*"
+               Condition="'$(ImportByWildcardBeforeMicrosoftCommonTargets)' == 'true' and Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportBefore')"/>
+
+       <Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')"/>
+
+       <PropertyGroup>
+               <OutputType Condition="'$(OutputType)' == ''">Exe</OutputType>
+               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <AssemblyName Condition="'$(AssemblyName)' == ''">$(MSBuildProjectName)</AssemblyName>
+               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath>
+               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
+               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
+
+               <TargetFrameworkIdentifier Condition="'$(TargetFrameworkIdentifier)' == ''">.NETFramework</TargetFrameworkIdentifier>
+               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v4.0</TargetFrameworkVersion>
+
+               <TargetFrameworkMoniker Condition="'$(TargetFrameworkMoniker)' == '' and '$(TargetFrameworkProfile)' != ''">$(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion),Profile=$(TargetFrameworkProfile)</TargetFrameworkMoniker>
+               <TargetFrameworkMoniker Condition="'$(TargetFrameworkMoniker)' == ''">$(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion)</TargetFrameworkMoniker>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
+               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
+
+               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
+               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
+
+               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
+               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+
+               <AddAdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == ''">true</AddAdditionalExplicitAssemblyReferences>
+               <AdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == 'true' and '$(TargetFrameworkVersion)' != 'v2.0' and '$(TargetFrameworkVersion)' != 'v3.0'">System.Core;$(AdditionalExplicitAssemblyReferences)</AdditionalExplicitAssemblyReferences>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <SkipCopyUnchangedFiles Condition="'$(SkipCopyUnchangedFiles)' == ''">true</SkipCopyUnchangedFiles>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' != '' and !HasTrailingSlash('$(BaseIntermediateOutputPath)')">$(BaseIntermediateOutputPath)\</BaseIntermediateOutputPath>
+               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
+               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
+               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <IntermediateOutputPath Condition="'$(IntermediateOutputPath)' != '' and !HasTrailingSlash('$(IntermediateOutputPath)')">$(IntermediateOutputPath)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
+
+               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
+               <_OutDirItem Include="$(OutDir)"/>
+       </ItemGroup>
+
+       <PropertyGroup>
+               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
+               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
+               <TargetDir Condition=" '$(TargetDir)' == '' ">@(_OutDirItem->'%(FullPath)')</TargetDir>
+               <TargetPath Condition=" '$(TargetPath)' == '' ">@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
+               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets</MSBuildAllProjects>
+               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
+               <TargetingClr2Framework Condition="('$(TargetFrameworkIdentifier)' == '.NETFramework') and ('$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5')">true</TargetingClr2Framework>
+       </PropertyGroup>
+
+       <Target Name="_ValidateEssentialProperties">
+               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <!-- If OutDir is specified via the command line, then the earlier check
+                    to add a trailing slash won't have any affect, so error here. -->
+               <Error
+                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
+                       Text="OutDir property must end with a slash."/>
+       </Target>
+
+       <Target Name="PrepareForBuild">
+               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
+
+               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
+                    @(None) and @(Content) -->
+               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
+                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
+                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
+               </CreateItem>
+
+               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
+                       Condition="'$(AppConfig)' == ''">
+                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
+               </FindAppConfigFile>
+
+               <MakeDir
+                       Directories="$(OutDir);$(IntermediateOutputPath);@(DocFileItem->'%(RelativeDir)')"
+               />
+       </Target>
+
+       <PropertyGroup>
+               <GetFrameworkPathsDependsOn />
+       </PropertyGroup>
+       <Target Name="GetFrameworkPaths"
+               Condition="'$(TargetFrameworkIdentifier)' == '' or '$(TargetFrameworkIdentifier)' == '.NETFramework'"
+               DependsOnTargets="$(GetFrameworkPathsDependsOn)">
+               <GetFrameworkPath>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v4.5'"
+                               TaskParameter="FrameworkVersion45Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v4.0'"
+                               TaskParameter="FrameworkVersion40Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion35Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion30Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion20Path"
+                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
+               </GetFrameworkPath>
+               <CreateProperty Value="@(_CombinedTargetFrameworkDirectoriesItem)">
+                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
+               </CreateProperty>
+
+               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
+                       Condition="'$(TargetFrameworkVersion)' != 'v4.5' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
+       </Target>
+
+       <PropertyGroup>
+               <GetReferenceAssemblyPathsDependsOn />
+       </PropertyGroup>
+       <Target Name="GetReferenceAssemblyPaths" DependsOnTargets="$(GetReferenceAssemblyPathsDependsOn)">
+               <!-- in case of .NETFramework, $(TargetFrameworkDirectory) would have been set by
+               GetFrameworkPaths, if it hasn't been changed, then clear it, to avoid duplicates -->
+               <CreateProperty Value="" Condition="'@(_CombinedTargetFrameworkDirectoriesItem)' == '$(TargetFrameworkDirectory)'">
+                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
+               </CreateProperty>
+
+               <GetReferenceAssemblyPaths
+                       Condition="'$(TargetFrameworkMoniker)' != '' and '$(_TargetFrameworkDirectories)' == ''"
+                       TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
+                       RootPath="$(TargetFrameworkRootPath)">
+
+                       <Output TaskParameter="ReferenceAssemblyPaths" PropertyName="_TargetFrameworkDirectories"/>
+                       <Output TaskParameter="FullFrameworkReferenceAssemblyPaths" PropertyName="_FullFrameworkReferenceAssemblyPaths"/>
+                       <Output TaskParameter="TargetFrameworkMonikerDisplayName" PropertyName="TargetFrameworkMonikerDisplayName"/>
+               </GetReferenceAssemblyPaths>
+
+
+               <!-- Remove duplicates. -->
+               <ItemGroup>
+                       <_TargetFrameworkDirectories Include="$(_TargetFrameworkDirectories);$(TargetFrameworkDirectory)" KeepDuplicates="false" />
+               </ItemGroup>
+               <PropertyGroup>
+                       <TargetFrameworkDirectory>@(_TargetFrameworkDirectories)</TargetFrameworkDirectory>
+               </PropertyGroup>
+
+               <ItemGroup Condition="'$(ImplicitlyExpandDesignTimeFacades)' == 'true'">
+                       <DesignTimeFacadeDirectoryRoots Include="$(TargetFrameworkDirectory)" />
+                       <DesignTimeFacadeDirectories Include="%(DesignTimeFacadeDirectoryRoots.Identity)\Facades\" Condition="Exists('%(DesignTimeFacadeDirectoryRoots.Identity)\Facades\')" />
+                       <_DesignTimeFacadeAssemblies Include="%(DesignTimeFacadeDirectories.Identity)\*.dll"/>
+               </ItemGroup>
+
+               <PropertyGroup Condition="'@(DesignTimeFacadeDirectories)' != ''">
+                       <TargetFrameworkDirectory>$(TargetFrameworkDirectory);@(DesignTimeFacadeDirectories)</TargetFrameworkDirectory>
+               </PropertyGroup>
+
+       </Target>
+
+       <PropertyGroup>
+               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
+                       .exe;
+                       .dll
+               </AllowedReferenceAssemblyFileExtensions>
+
+               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
+                       .exe.mdb;
+                       .dll.mdb;
+                       .xml
+               </AllowedReferenceRelatedFileExtensions>
+
+               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
+                       {CandidateAssemblyFiles};
+                       $(ReferencePath);
+                       @(AdditionalReferencePath);
+                       {HintPathFromItem};
+                       {TargetFrameworkDirectory};
+                       {PkgConfig};
+                       {GAC};
+                       {RawFileName};
+                       $(OutDir)
+               </AssemblySearchPaths>
+
+               <ResolveReferencesDependsOn>
+                       BeforeResolveReferences;
+                       ResolveProjectReferences;
+                       ResolveAssemblyReferences;
+                       AfterResolveReferences
+               </ResolveReferencesDependsOn>
+
+               <ResolveAssemblyReferencesDependsOn>
+                       GetFrameworkPaths;
+                       GetReferenceAssemblyPaths;
+                       PrepareForBuild
+               </ResolveAssemblyReferencesDependsOn>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(TargetFrameworkMoniker)' != ''">
+               <TargetFrameworkMonikerAssemblyAttributesPath Condition="'$(TargetFrameworkMonikerAssemblyAttributesPath)' == ''">$(IntermediateOutputPath)$(TargetFrameworkMoniker).AssemblyAttribute$(DefaultLanguageSourceExtension)</TargetFrameworkMonikerAssemblyAttributesPath>
+               <GenerateTargetFrameworkAttribute Condition="'$(GenerateTargetFrameworkAttribute)' == '' and '$(TargetFrameworkMoniker)'
+       != '' and '$(TargetingClr2Framework)' != 'true'">true</GenerateTargetFrameworkAttribute>
+       </PropertyGroup>
+
+       <ItemGroup Condition="'$(GenerateTargetFrameworkAttribute)' == 'true'">
+               <FileWrites Include="$(TargetFrameworkMonikerAssemblyAttributesPath)" />
+       </ItemGroup>
+
+       <Target Name="GenerateTargetFrameworkMonikerAttribute"
+               DependsOnTargets="PrepareForBuild;GetReferenceAssemblyPaths"
+               Inputs="$(MSBuildToolsPath)\Microsoft.Common.targets"
+               Outputs="$(TargetFrameworkMonikerAssemblyAttributesPath)"
+               Condition="'$(GenerateTargetFrameworkAttribute)' == 'true'">
+
+               <WriteLinesToFile
+                       File="$(TargetFrameworkMonikerAssemblyAttributesPath)"
+                       Lines="$(TargetFrameworkMonikerAssemblyAttributeText)"
+                       Overwrite="true"
+                       ContinueOnError="true"
+                       Condition="'@(Compile)' != '' and '$(TargetFrameworkMonikerAssemblyAttributeText)' != ''"
+               />
+
+               <ItemGroup Condition="'@(Compile)' != '' and '$(TargetFrameworkMonikerAssemblyAttributeText)' != ''">
+                       <Compile Include="$(TargetFrameworkMonikerAssemblyAttributesPath)"/>
+               </ItemGroup>
+       </Target>
+
+       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
+
+       <Target Name="BeforeResolveReferences" />
+       <Target Name="AfterResolveReferences" />
+
+       <Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
+               <CreateItem Include="@(Reference)" Exclude="$(AdditionalExplicitAssemblyReferences)">
+                       <Output TaskParameter="Include" ItemName="_Reference"/>
+               </CreateItem>
+
+               <CreateItem Include="$(AdditionalExplicitAssemblyReferences)">
+                       <Output TaskParameter="Include" ItemName="_Reference"/>
+               </CreateItem>
+
+               <ResolveAssemblyReference
+                       Assemblies="@(_Reference)"
+                       AssemblyFiles="@(ChildProjectReferences)"
+                       SearchPaths="$(AssemblySearchPaths)"
+                       CandidateAssemblyFiles="@(Content);@(None)"
+                       TargetFrameworkDirectories="$(TargetFrameworkDirectory)"
+                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
+                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
+                       FindDependencies="true"
+                       FindSatellites="true"
+                       FindRelatedFiles="true"
+                       TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
+                       TargetFrameworkMonikerDisplayName="$(TargetFrameworkMonikerDisplayName)"
+                       TargetFrameworkVersion="$(TargetFrameworkVersion)"
+               >
+                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
+                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="ReferenceDependencyPaths"/>
+                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
+                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
+                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
+
+                       <!-- FIXME: backwards compatibility -->
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
+               </ResolveAssemblyReference>
+       </Target>
+
+       <Target
+               Name="AssignProjectConfiguration"
+               Condition="'@(ProjectReference)' != ''">
+
+               <!-- assign configs if building a solution file -->
+               <AssignProjectConfiguration
+                       ProjectReferences = "@(ProjectReference)"
+                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
+                       Condition="'$(BuildingSolutionFile)' == 'true'">
+
+                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
+               </AssignProjectConfiguration>
+
+               <!-- Else, just -->
+               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Split projects into 2 lists
+               ProjectReferenceWithConfigurationExistent: Projects existent on disk
+               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
+
+       <Target Name="SplitProjectReferencesByExistent"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
+                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
+                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+               </CreateItem>
+       </Target>
+
+       <Target
+               Name="ResolveProjectReferences"
+               DependsOnTargets="SplitProjectReferencesByExistent"
+       >
+               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
+                    been built, so just get the target paths -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetTargetPath"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <!-- Building a project directly, build the referenced the projects also -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
+                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
+       </Target>
+
+       <Target Name = "CopyFilesMarkedCopyLocal">
+               <Copy
+                       SourceFiles="@(ReferenceCopyLocalPaths)"
+                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWritesShareable"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
+               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
+                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
+               </CreateProperty>
+       </Target>
+
+       <PropertyGroup>
+               <BuildDependsOn>
+                       BuildOnlySettings;
+                       BeforeBuild;
+                       CoreBuild;
+                       AfterBuild
+               </BuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BuildOnlySettings"/>
+       <Target Name="BeforeBuild"/>
+       <Target Name="AfterBuild"/>
+
+       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
+
+       <PropertyGroup>
+               <CoreBuildDependsOn>
+                       PrepareForBuild;
+                       GetFrameworkPaths;
+                       GetReferenceAssemblyPaths;
+                       PreBuildEvent;
+                       ResolveReferences;
+                       CopyFilesMarkedCopyLocal;
+                       PrepareResources;
+                       Compile;
+                       PrepareForRun;
+                       DeployOutputFiles;
+                       _RecordCleanFile;
+                       PostBuildEvent
+               </CoreBuildDependsOn>
+       </PropertyGroup>
+
+       <Target
+               Name="CoreBuild"
+               DependsOnTargets="$(CoreBuildDependsOn)"
+               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
+
+               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
+                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
+
+               <OnError ExecuteTargets="_RecordCleanFile" />
+       </Target>
+
+       <PropertyGroup>
+               <CompileDependsOn>
+                       ResolveReferences;
+                       GenerateTargetFrameworkMonikerAttribute;
+                       BeforeCompile;
+                       _TimestampBeforeCompile;
+                       CoreCompile;
+                       _TimestampAfterCompile;
+                       AfterCompile
+               </CompileDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeCompile" />
+       <Target Name="AfterCompile" />
+
+       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareForRunDependsOn>
+                       DeployOutputFiles
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       AssignTargetPaths;
+                       SplitResourcesByCulture;
+                       CreateManifestResourceNames;
+                       CopyNonResxEmbeddedResources;
+                       GenerateResources;
+                       GenerateSatelliteAssemblies;
+                       CompileLicxFiles
+               </PrepareResourcesDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
+
+       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
+               <!-- Extract .licx files into @(LicxFiles) -->
+               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
+                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
+               </CreateItem>
+
+               <!-- Split *remaining* resource files into various groups.. -->
+               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
+                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
+                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
+               </AssignCulture>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
+       <Target Name = "CopyNonResxEmbeddedResources"
+               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
+
+               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
+               <Copy SourceFiles = "@(NonResxWithCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles = "@(NonResxWithNoCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name = "GenerateResources">
+               <GenerateResource
+                       Sources = "@(ResxWithNoCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithNoCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+
+               <GenerateResource
+                       Sources = "@(ResxWithCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+       </Target>
+
+       <Target Name="GenerateSatelliteAssemblies"
+               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
+
+               <AL
+                       Culture = "%(Culture)"
+                       DelaySign="$(DelaySign)"
+                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       ToolExe="$(AlToolExe)"
+                       ToolPath="$(AlToolPath)"
+                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
+               </AL>
+
+
+               <CreateItem
+                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
+                       AdditionalMetadata = "Culture=%(Culture)"
+                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
+                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
+               </CreateItem>
+       </Target>
+
+       <PropertyGroup>
+               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
+       </PropertyGroup>
+
+       <Target Name = "CompileLicxFiles"
+               Condition = "'@(LicxFiles)' != ''"
+               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
+               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
+               <LC
+                       Sources = "@(LicxFiles)"
+                       LicenseTarget = "$(TargetFileName)"
+                       OutputDirectory = "$(IntermediateOutputPath)"
+                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
+                       ReferencedAssemblies = "@(ReferencePath);@(ReferenceDependencyPaths)"
+                       ToolPath = "$(LCToolPath)"
+                       ToolExe = "$(LCToolExe)">
+
+                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
+                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
+               </LC>
+       </Target>
+
+       <!-- Assign target paths to files that will need to be copied along with the project -->
+       <Target Name = "AssignTargetPaths">
+               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
+               </AssignTargetPath>
+       </Target>
+
+       <Target Name="DeployOutputFiles"
+               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
+
+               <Copy
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(OutDir)"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)" >
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_CopyDeployFilesToOutputDirectory"
+               DependsOnTargets="GetCopyToOutputDirectoryItems;
+                       _CopyDeployFilesToOutputDirectoryAlways;
+                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
+
+       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
+               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
+               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')"
+                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <!-- Copy if newer -->
+       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
+               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+
+       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
+               Inputs="@(AppConfigWithTargetPath)"
+               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(AppConfigWithTargetPath)"
+                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
+
+       <Target Name="GetCopyToOutputDirectoryItems"
+               Outputs="@(AllItemsFullPathWithTargetPath)"
+               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
+
+               <!-- FIXME: handle .vcproj
+                    FIXME: Private ProjectReferences are honored only in 3.5
+               -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetCopyToOutputDirectoryItems"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
+               </MSBuild>
+
+               <!-- Process items from child project. The outputs need to have full path
+                    as they'll be used from other projects -->
+
+               <CreateItem
+                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
+                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+
+               </CreateItem>
+
+               <!-- Process _this_ project's items -->
+
+               <CreateItem
+                       Include="@(NoneWithTargetPath->'%(FullPath)')"
+                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(ContentWithTargetPath->'%(FullPath)')"
+                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
+                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Pre/Post BuildEvents -->
+       <PropertyGroup>
+               <PreBuildEventDependsOn />
+       </PropertyGroup>
+
+       <Target Name="PreBuildEvent"
+               Condition="'$(PreBuildEvent)' != ''"
+               DependsOnTargets="$(PreBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
+       </Target>
+
+       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
+
+               Default: OnBuildSuccess
+               OnBuildSuccess: Run after a successful build
+               OnOutputUpdated: Run only if the output assembly got updates
+               Always: Run always
+       -->
+       <PropertyGroup>
+               <PostBuildEventDependsOn />
+       </PropertyGroup>
+
+       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
+            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
+            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
+            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
+       <Target Name="PostBuildEvent"
+               Condition="'$(PostBuildEvent)' != '' and
+                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
+                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
+               DependsOnTargets="$(PostBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
+       </Target>
+
+       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
+       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
+               </CreateItem>
+       </Target>
+       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
+               </CreateItem>
+       </Target>
+
+       <!-- Rebuild -->
+       <PropertyGroup>
+               <RebuildDependsOn>
+                       BeforeRebuild;
+                       Clean;
+                       $(MSBuildProjectDefaultTargets);
+                       AfterRebuild;
+               </RebuildDependsOn>
+
+               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
+                       BeforeRebuild;
+                       Clean;
+                       Build;
+                       AfterRebuild;
+               </RebuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeRebuild" />
+       <Target Name="AfterRebuild" />
+
+       <Target Name="Rebuild"
+               DependsOnTargets="$(RebuildDependsOn)"
+               Outputs="$(TargetPath)"/>
+
+       <!-- Clean -->
+       <Target Name="_RecordCleanFile"
+               DependsOnTargets="_GetCompileOutputsForClean">
+
+               <!-- add to list of previous writes for this platform/config -->
+
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+
+               <!-- CopyLocal files: In case all the projects build to common output
+                    directory, then other projects might depend on some of these
+                    CopyLocal files, so delete only the ones under *this* project
+                    directory -->
+               <FindUnderPath Path="$(MSBuildProjectDirectory)" Files="@(FileWritesShareable)">
+                       <Output TaskParameter="InPath" ItemName="FileWrites"/>
+               </FindUnderPath>
+
+               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
+                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
+               </RemoveDuplicates>
+
+               <WriteLinesToFile
+                       File="$(IntermediateOutputPath)$(CleanFile)"
+                       Lines="@(CombinedFileWrites)"
+                       Overwrite="true"/>
+       </Target>
+
+       <PropertyGroup>
+               <CleanDependsOn>
+                       BeforeClean;
+                       CleanReferencedProjects;
+                       CoreClean;
+                       AfterClean
+               </CleanDependsOn>
+       </PropertyGroup>
+
+       <Target Name="_GetCompileOutputsForClean">
+               <!-- assembly and debug file in the *intermediate output path* -->
+               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Get the list of files written, for clean -->
+       <Target Name="_GetCleanFileWrites"
+               DependsOnTargets="_GetCompileOutputsForClean">
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+       </Target>
+
+       <Target Name="CleanReferencedProjects"
+               DependsOnTargets="AssignProjectConfiguration">
+
+               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
+                    else we are building a project directly, from the command line, so
+                    clean the referenced projects -->
+               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="Clean"
+                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
+
+       </Target>
+
+       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
+
+       <!-- Override in project to run before/after clean tasks -->
+       <Target Name="BeforeClean" />
+       <Target Name="AfterClean" />
+
+       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
+               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
+
+               <!-- all previous files written for this platform/config have been deleted,
+                    we can safely remove the file list now -->
+               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
+       </Target>
+
+       <PropertyGroup>
+               <ImplicitlyExpandDesignTimeFacades>true</ImplicitlyExpandDesignTimeFacades>
+
+               <ResolveReferencesDependsOn>
+                       $(ResolveReferencesDependsOn);
+                       ImplicitlyExpandDesignTimeFacades
+               </ResolveReferencesDependsOn>
+
+               <ImplicitlyExpandDesignTimeFacadesDependsOn>
+                       $(ImplicitlyExpandDesignTimeFacadesDependsOn);
+                       GetReferenceAssemblyPaths
+               </ImplicitlyExpandDesignTimeFacadesDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ImplicitlyExpandDesignTimeFacades" Condition="'$(ImplicitlyExpandDesignTimeFacades)' == 'true'" DependsOnTargets="$(ImplicitlyExpandDesignTimeFacadesDependsOn)">
+
+               <PropertyGroup>
+                       <_HasReferenceToSystemRuntime Condition="'%(_ResolvedDependencyFiles.Filename)' == 'System.Runtime'">true</_HasReferenceToSystemRuntime>
+               </PropertyGroup>
+
+               <ItemGroup Condition="'$(_HasReferenceToSystemRuntime)' == 'true'">
+                       <!-- If the user has manually referenced these assemblies, remove them so we don't end up with duplicates -->
+                       <ReferencePath Remove="@(_DesignTimeFacadeAssemblies)"/>
+                       <ReferencePath Include="%(_DesignTimeFacadeAssemblies.Identity)">
+                               <WinMDFile>false</WinMDFile>
+                               <CopyLocal>false</CopyLocal>
+                               <ResolvedFrom>ImplicitlyExpandDesignTimeFacades</ResolvedFrom>
+                       </ReferencePath>
+                       <_ResolveAssemblyReferenceResolvedFiles Include="@(ReferencePath)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandDesignTimeFacades'" />
+               </ItemGroup>
+
+               <Message Importance="Low" Text="Including @(ReferencePath)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandDesignTimeFacades'" />
+
+       </Target>
+
+       <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportAfter\*"
+               Condition="'$(ImportByWildcardAfterMicrosoftCommonTargets)' == 'true' and Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportAfter')"/>
+</Project>
diff --git a/mcs/tools/xbuild/data/4.0/Microsoft.Common.tasks b/mcs/tools/xbuild/data/4.0/Microsoft.Common.tasks
new file mode 100644 (file)
index 0000000..d326aad
--- /dev/null
@@ -0,0 +1,35 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateCSharpManifestResourceName"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetReferenceAssemblyPaths"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+</Project>
diff --git a/mcs/tools/xbuild/data/MSBuild/Microsoft.Build.CommonTypes.xsd b/mcs/tools/xbuild/data/MSBuild/Microsoft.Build.CommonTypes.xsd
new file mode 100644 (file)
index 0000000..148f6bf
--- /dev/null
@@ -0,0 +1,1581 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xs:schema targetNamespace="http://schemas.microsoft.com/developer/msbuild/2003" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003"
+elementFormDefault="qualified">
+
+    <!-- =================== INCLUDE COMMON SCHEMA =========================== -->
+    <xs:include schemaLocation="Microsoft.Build.Core.xsd"/>
+
+    <!-- ======================== ITEMS =====================================-->
+    <!-- Possible Types include SimpleItemType (no meta-data subelements), GenericItemType (any meta-data), or something more specific.-->
+    <xs:element name="Reference" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Reference to an assembly</xs:documentation>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="HintPath">
+                                <xs:annotation>
+                                    <xs:documentation>Relative or absolute path to the assembly (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Name">
+                                <xs:annotation>
+                                    <xs:documentation>Friendly display name (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="FusionName">
+                                <xs:annotation>
+                                    <xs:documentation>Fusion name of the assembly (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="SpecificVersion">
+                                <xs:annotation>
+                                    <xs:documentation>Whether only the version in the fusion name should be referenced (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Aliases">
+                                <xs:annotation>
+                                    <xs:documentation>Aliases for the reference (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Private">
+                                <xs:annotation>
+                                    <xs:documentation>Whether the reference should be copied to the output folder (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                        </xs:choice>
+                    </xs:sequence>
+                    <!-- redefine Include just to give a specific description -->
+                    <xs:attribute name="Include" type="xs:string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>Assembly name or filename</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="COMReference" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Reference to a COM component</xs:documentation>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="Name">
+                                <xs:annotation>
+                                    <xs:documentation>Friendly display name (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Guid">
+                                <xs:annotation>
+                                    <xs:documentation>GUID in the form {00000000-0000-0000-0000-000000000000}</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="VersionMajor">
+                                <xs:annotation>
+                                    <xs:documentation>Major part of the version number</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="VersionMinor">
+                                <xs:annotation>
+                                    <xs:documentation>Minor part of the version number</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Lcid">
+                                <xs:annotation>
+                                    <xs:documentation>Locale ID</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="WrapperTool">
+                                <xs:annotation>
+                                    <xs:documentation>Wrapper tool, such as tlbimp</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Isolated">
+                                <xs:annotation>
+                                    <xs:documentation>Is it isolated (boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                        </xs:choice>
+                    </xs:sequence>
+                    <!-- redefine Include just to give a specific description -->
+                    <xs:attribute name="Include" type="xs:string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>COM component name</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="COMFileReference" substitutionGroup="msb:Item">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="WrapperTool"/>
+                        </xs:choice>
+                    </xs:sequence>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="NativeReference" substitutionGroup="msb:Item">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="Name"/>
+                            <xs:element name="HintPath"/>
+                        </xs:choice>
+                    </xs:sequence>
+                    <!-- redefine Include just to give a specific description -->
+                    <xs:attribute name="Include" type="xs:string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>Path to native reference</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ProjectReference" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Reference to another project</xs:documentation>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="Name">
+                                <xs:annotation>
+                                    <xs:documentation>Friendly display name (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Project">
+                                <xs:annotation>
+                                    <xs:documentation>Project GUID, in the form {00000000-0000-0000-0000-000000000000}</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Package"/>
+                        </xs:choice>
+                    </xs:sequence>
+                    <!-- redefine Include just to give a specific description -->
+                    <xs:attribute name="Include" type="xs:string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>Path to project file</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Compile" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Source files for compiler</xs:documentation>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="SubType"/>
+                            <xs:element name="DependentUpon"/>
+                            <xs:element name="AutoGen">
+                                <xs:annotation>
+                                    <xs:documentation>Whether file was generated from another file (boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="DesignTime"/>
+                            <xs:element name="Link">
+                                <xs:annotation>
+                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="DesignTimeSharedInput"/>
+                            <xs:element name="InProject">
+                                <xs:annotation>
+                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                        </xs:choice>
+                    </xs:sequence>
+                    <!-- redefine Include just to give a specific description -->
+                    <xs:attribute name="Include" type="xs:string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>Semi-colon separated list of source files (wildcards are allowed)</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="EmbeddedResource" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Resources to be embedded in the generated assembly</xs:documentation>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="DependentUpon"/>
+                            <xs:element name="Generator">
+                                <xs:annotation>
+                                    <xs:documentation>Name of any file generator that is run on this item</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="LastGenOutput">
+                                <xs:annotation>
+                                    <xs:documentation>File that was created by any file generator that was run on this item</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="CustomToolNamespace">
+                                <xs:annotation>
+                                    <xs:documentation>Namespace into which any file generator that is run on this item should create code</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Link">
+                                <xs:annotation>
+                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="InProject">
+                                <xs:annotation>
+                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="SubType"/>
+                        </xs:choice>
+                    </xs:sequence>
+                    <!-- redefine Include just to give a specific description -->
+                    <xs:attribute name="Include" type="xs:string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>Semi-colon separated list of resource files (wildcards are allowed)</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Content" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Files that are not compiled, but may be embedded or published</xs:documentation>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="DependentUpon"/>
+                            <xs:element name="Generator">
+                                <xs:annotation>
+                                    <xs:documentation>Name of any file generator that is run on this item</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="LastGenOutput"/>
+                            <xs:element name="CustomToolNamespace"/>
+                            <xs:element name="Link">
+                                <xs:annotation>
+                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Group"/>
+                            <xs:element name="PublishState">
+                            <xs:annotation>
+                                <xs:documentation>Default, Included, Excluded, DataFile, or Prerequisite</xs:documentation>
+                            </xs:annotation>
+                            </xs:element>
+                            <xs:element name="IsAssembly"/>
+                            <xs:element name="InProject">
+                                <xs:annotation>
+                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="SubType"/>
+                            <xs:element name="CopyToOutputDirectory">
+                                <xs:annotation>
+                                    <xs:documentation>Copy file to output directory (optional, boolean, default false)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                        </xs:choice>
+                    </xs:sequence>
+                    <!-- redefine Include just to give a specific description -->
+                    <xs:attribute name="Include" type="xs:string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>Semi-colon separated list of content files (wildcards are allowed)</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="None" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Files that should have no role in the build process</xs:documentation>
+        </xs:annotation>
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <!-- UNDONE. Remove all but Link when #318721 is fixed-->
+                            <xs:element name="DependentUpon"/>
+                            <xs:element name="Generator">
+                                <xs:annotation>
+                                    <xs:documentation>Name of any file generator that is run on this item</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="LastGenOutput"/>
+                            <xs:element name="CustomToolNamespace"/>
+                            <xs:element name="Link">
+                                <xs:annotation>
+                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="InProject">
+                                <xs:annotation>
+                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                        </xs:choice>
+                    </xs:sequence>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Folder" type="msb:SimpleItemType" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Folder on disk</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="Import" type="msb:SimpleItemType" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Assemblies whose namespaces should be imported by the Visual Basic compiler</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="Service" type="msb:SimpleItemType" substitutionGroup="msb:Item"/>
+    <xs:element name="WebReferences" type="msb:SimpleItemType" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Name of Web References folder to display in user interface</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="WebReferenceUrl" substitutionGroup="msb:Item">
+        <xs:annotation>
+            <xs:documentation>Represents a reference to a web service</xs:documentation>
+        </xs:annotation>
+            <xs:complexType>
+                <xs:complexContent>
+                    <xs:extension base="msb:SimpleItemType">
+                        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                            <xs:choice>
+                                <xs:element name="UrlBehavior"/>
+                                <xs:element name="RelPath"/>
+                                <xs:element name="UpdateFromURL"/>
+                                <xs:element name="ServiceLocationURL"/>
+                                <xs:element name="CachedDynamicPropName"/>
+                                <xs:element name="CachedAppSettingsObjectName"/>
+                                <xs:element name="CachedSettingsPropName"/>
+                            </xs:choice>
+                        </xs:sequence>
+                        <!-- redefine Include just to give a specific description -->
+                        <xs:attribute name="Include" type="xs:string" use="required">
+                            <xs:annotation>
+                                <xs:documentation>URL to web service</xs:documentation>
+                            </xs:annotation>
+                        </xs:attribute>
+                    </xs:extension>
+                </xs:complexContent>
+            </xs:complexType>
+    </xs:element>
+    <xs:element name="BootstrapperFile" substitutionGroup="msb:Item">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="InProject">
+                                <xs:annotation>
+                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="ProductName"/>
+                            <xs:element name="Install"/>
+                        </xs:choice>
+                    </xs:sequence>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="PublishFile" substitutionGroup="msb:Item">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                        <xs:choice>
+                            <xs:element name="InProject">
+                                <xs:annotation>
+                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="Group"/>
+                            <xs:element name="IsAssembly">
+                                <xs:annotation>
+                                    <xs:documentation>(boolean)</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                            <xs:element name="PublishState">
+                                <xs:annotation>
+                                    <xs:documentation>Default, Included, Excluded, DataFile, or Prerequisite</xs:documentation>
+                                </xs:annotation>
+                            </xs:element>
+                        </xs:choice>
+                    </xs:sequence>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <!-- ======================== PROPERTIES =====================================-->
+    <!-- Possible Types include StringPropertyType (text with no subelements), GenericPropertyType (any content), or something more specific.-->
+    <xs:element name="AllowUnsafeBlocks" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ApplicationIcon" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ApplicationRevision" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>integer</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="ApplicationVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Matches the expression "\d\.\d\.\d\.(\d|\*)"</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="AppDesignerFolder" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Name of folder for Application Designer</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="AssemblyKeyContainerName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="AssemblyKeyProviderName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="AssemblyName" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Name of output assembly</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="AssemblyOriginatorKeyFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="AssemblyOriginatorKeyFileType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="AssemblyOriginatorKeyMode" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="AssemblyType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="AutorunEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="BaseAddress" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="BootstrapperComponentsLocation" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>HomeSite, Relative, or Absolute</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="BootstrapperComponentsUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="BootstrapperEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="CheckForOverflowUnderflow" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="CodePage" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="Configuration" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ConfigurationOverrideFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="CreateWebPageOnPublish" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="DebugSecurityZoneURL" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DebugSymbols" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Whether to emit symbols (boolean)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="DebugType" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>none, pdbonly, or full</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="DefaultClientScript" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DefaultHTMLPageLayout" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DefaultTargetSchema" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DefineConstants" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DefineDebug" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Whether DEBUG is defined (boolean)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="DefineTrace" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Whether TRACE is defined (boolean)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="DelaySign" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DisableLangXtns" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DisallowUrlActiviation" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="DeployDirSuffix" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="DocumentationFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="EnableASPDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="EnableASPXDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="EnableSQLServerDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="EnableSecurityDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="EnableUnmanagedDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ErrorReport" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ExcludedPermissions" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="FallbackCulture" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="FileAlignment" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="FileUpgradeFlags" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="FormFactorID" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="FxCopLogFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="FxCopProjectFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="FxCopRules" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="GenerateManifests" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="GenerateSerializationAssemblies" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="Install" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="InstallFrom" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Web, Unc, or Disk</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="InstallUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="IsWebBootstrapper" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="JCPA" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="LangVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ManifestCertificateThumbprint" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ManifestKeyFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="MapFileExtensions" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="MinimumRequiredVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Matches the expression "\d\.\d\.\d\.\d"</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="MyType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="NoConfig" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="NoStandardLibraries" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="NoStdLib" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Whether standard libraries (such as mscorlib) should be referenced automatically (boolean)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="NoWarn" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Comma separated list of disabled warnings</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="OpenBrowserOnPublish" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="Optimize" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Should compiler optimize output (boolean)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="OptionCompare" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Option Compare setting (Text or Binary)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="OptionExplicit" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Should Option Explicit be set (On or Off)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="OptionStrict" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Should Option Strict be set (On or Off)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="OSVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="OutputPath" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Path to output folder, with trailing slash</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="OutputType" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Type of output to generate (WinExe, Exe, or Library)</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="Platform" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="PlatformFamilyName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="PlatformID" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="PlatformTarget" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="PostBuildEvent" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Command line to be run at the end of build</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="PreBuildEvent" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Command line to be run at the start of build</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="ProductName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ProductVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ProjectGuid" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ProjectType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ProjectTypeGuids" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="PublisherName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="PublishUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="RecursePath" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ReferencePath" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Semi-colon separated list of folders to search during reference resolution</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="RegisterForComInterop" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="RemoteDebugEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="RemoteDebugMachine" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="RemoveIntegerChecks" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="ResponseFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="RootNamespace" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="RunFxCop" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="RunPostBuildEvent" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="SchemaVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="SecureScoping" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="SignAssembly" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="SignManifests" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartAction" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartArguments" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartPage" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartProgram" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartURL" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartWithIE" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartWorkingDirectory" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="StartupObject" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Type that contains the main entry point</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="SupportUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="TargetCulture" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="TargetZone" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="TreatWarningsAsErrors" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="TrustUrlParameters" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="TypeComplianceDiagnostics" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="UpdateEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="UpdateInterval" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="UpdateIntervalUnits" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Hours, Days, or Weeks</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="UpdateMode" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Foreground or Background</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="UpdatePeriodically" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="UpdateRequired" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>boolean</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="UpdateUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="UTF8OutPut" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="UseVSHostingProcess" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="VSTO_TrustAssembliesLocation" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="WarningLevel" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>integer between 0 and 4 inclusive</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="WarningsAsErrors" type="msb:StringPropertyType" substitutionGroup="msb:Property">
+        <xs:annotation>
+            <xs:documentation>Comma separated list of warning numbers to treat as errors</xs:documentation>
+        </xs:annotation>
+    </xs:element>
+    <xs:element name="WebPage" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <xs:element name="Win32ResourceFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
+    <!-- ======================== TASKS =====================================-->
+    <xs:element name="AL" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="OutputAssembly" use="required" />
+                    <xs:attribute name="AlgorithmId" />
+                    <xs:attribute name="BaseAddress" />
+                    <xs:attribute name="CompanyName" />
+                    <xs:attribute name="Configuration" />
+                    <xs:attribute name="Copyright" />
+                    <xs:attribute name="Culture" />
+                    <xs:attribute name="DelaySign" />
+                    <xs:attribute name="Description" />
+                    <xs:attribute name="EmbedResources" />
+                    <xs:attribute name="EvidenceFile" />
+                    <xs:attribute name="FileVersion" />
+                    <xs:attribute name="Flags" />
+                    <xs:attribute name="GenerateFullPaths" />
+                    <xs:attribute name="KeyContainer" />
+                    <xs:attribute name="KeyFile" />
+                    <xs:attribute name="LinkResources" />
+                    <xs:attribute name="MainEntryPoint" />
+                    <xs:attribute name="Platform" />
+                    <xs:attribute name="ProductName" />
+                    <xs:attribute name="ProductVersion" />
+                    <xs:attribute name="ResponseFiles" />
+                    <xs:attribute name="SourceModules" />
+                    <xs:attribute name="TargetType" />
+                    <xs:attribute name="TemplateFile" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="Title" />
+                    <xs:attribute name="ToolPath" />
+                    <xs:attribute name="Trademark" />
+                    <xs:attribute name="Version" />
+                    <xs:attribute name="Win32Icon" />
+                    <xs:attribute name="Win32Resource" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="AspNetCompiler" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Clean" />
+                    <xs:attribute name="Debug" />
+                    <xs:attribute name="Force" />
+                    <xs:attribute name="MetabasePath" />
+                    <xs:attribute name="PhysicalPath" />
+                    <xs:attribute name="TargetPath" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                    <xs:attribute name="Updateable" />
+                    <xs:attribute name="VirtualPath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="AssignCulture" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Files" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="AssignTargetPath" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="RootFolder" use="required" />
+                    <xs:attribute name="Files" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Copy" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="DestinationFiles" />
+                    <xs:attribute name="DestinationFolder" />
+                    <xs:attribute name="SkipUnchangedFiles" />
+                    <xs:attribute name="SourceFiles" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="CreateCSharpManifestResourceName" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="ResourceFiles" use="required" />
+                    <xs:attribute name="RootNamespace" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="CreateItem" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AdditionalMetadata" />
+                    <xs:attribute name="Exclude" />
+                    <xs:attribute name="Include" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="CreateJSharpManifestResourceName" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="ResourceFiles" use="required" />
+                    <xs:attribute name="RootNamespace" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="CreateProperty" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Value" />
+                    <xs:attribute name="ValueSetByTask" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="CreateVisualBasicManifestResourceName" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="ResourceFiles" use="required" />
+                    <xs:attribute name="RootNamespace" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Csc" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AdditionalLibPaths" />
+                    <xs:attribute name="AddModules" />
+                    <xs:attribute name="AllowUnsafeBlocks" />
+                    <xs:attribute name="BaseAddress" />
+                    <xs:attribute name="CheckForOverflowUnderflow" />
+                    <xs:attribute name="CodePage" />
+                    <xs:attribute name="DebugType" />
+                    <xs:attribute name="DefineConstants" />
+                    <xs:attribute name="DelaySign" />
+                    <xs:attribute name="DisabledWarnings" />
+                    <xs:attribute name="DocumentationFile" />
+                    <xs:attribute name="EmitDebugInformation" />
+                    <xs:attribute name="ErrorReport" />
+                    <xs:attribute name="FileAlignment" />
+                    <xs:attribute name="GenerateFullPaths" />
+                    <xs:attribute name="KeyContainer" />
+                    <xs:attribute name="KeyFile" />
+                    <xs:attribute name="LangVersion" />
+                    <xs:attribute name="LinkResources" />
+                    <xs:attribute name="MainEntryPoint" />
+                    <xs:attribute name="NoConfig" />
+                    <xs:attribute name="NoLogo" />
+                    <xs:attribute name="NoStandardLib" />
+                    <xs:attribute name="Optimize" />
+                    <xs:attribute name="OutputAssembly" />
+                    <xs:attribute name="Platform" />
+                    <xs:attribute name="References" />
+                    <xs:attribute name="Resources" />
+                    <xs:attribute name="ResponseFiles" />
+                    <xs:attribute name="Sources" />
+                    <xs:attribute name="TargetType" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                    <xs:attribute name="TreatWarningsAsErrors" />
+                    <xs:attribute name="UseHostCompilerIfAvailable" />
+                    <xs:attribute name="Utf8Output" />
+                    <xs:attribute name="WarningLevel" />
+                    <xs:attribute name="WarningsAsErrors" />
+                    <xs:attribute name="WarningsNotAsErrors" />
+                    <xs:attribute name="Win32Icon" />
+                    <xs:attribute name="Win32Resource" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Delete" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Files" use="required" />
+                    <xs:attribute name="DeletedFiles" />
+                    <xs:attribute name="TreatErrorsAsWarnings" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Error" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Text" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Exec" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Command" use="required" />
+                    <xs:attribute name="IgnoreExitCode" />
+                    <xs:attribute name="Outputs" />
+                    <xs:attribute name="StandardErrorEncoding" />
+                    <xs:attribute name="StandardOutputEncoding" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="WorkingDirectory" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="FindUnderPath" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Path" use="required" />
+                    <xs:attribute name="Files" />
+                    <xs:attribute name="InPath" />
+                    <xs:attribute name="OutOfPath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="FormatUrl" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="InputUrl" />
+                    <xs:attribute name="OutputUrl" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="FormatVersion" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="FormatType" />
+                    <xs:attribute name="OutputVersion" />
+                    <xs:attribute name="Revision" />
+                    <xs:attribute name="Version" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="FxCop" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="ApplyLogFileXsl" />
+                    <xs:attribute name="Assemblies" />
+                    <xs:attribute name="ConsoleXsl" />
+                    <xs:attribute name="DependentAssemblyPaths" />
+                    <xs:attribute name="Imports" />
+                    <xs:attribute name="LogFile" />
+                    <xs:attribute name="LogFileXsl" />
+                    <xs:attribute name="OutputToConsole" />
+                    <xs:attribute name="PlatformPath" />
+                    <xs:attribute name="Project" />
+                    <xs:attribute name="RuleAssemblies" />
+                    <xs:attribute name="Rules" />
+                    <xs:attribute name="Summary" />
+                    <xs:attribute name="ToolPath" />
+                    <xs:attribute name="UpdateProjectFile" />
+                    <xs:attribute name="Verbose" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GenerateApplicationManifest" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AssemblyName" />
+                    <xs:attribute name="AssemblyVersion" />
+                    <xs:attribute name="ClrVersion" />
+                    <xs:attribute name="ConfigFile" />
+                    <xs:attribute name="Dependencies" />
+                    <xs:attribute name="Description" />
+                    <xs:attribute name="EntryPoint" />
+                    <xs:attribute name="Files" />
+                    <xs:attribute name="IconFile" />
+                    <xs:attribute name="InputManifest" />
+                    <xs:attribute name="IsolatedComReferences" />
+                    <xs:attribute name="ManifestType" />
+                    <xs:attribute name="MaxTargetPath" />
+                    <xs:attribute name="OSVersion" />
+                    <xs:attribute name="OutputManifest" />
+                    <xs:attribute name="Platform" />
+                    <xs:attribute name="TargetCulture" />
+                    <xs:attribute name="TrustInfoFile" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GenerateBootstrapper" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="ApplicationFile" />
+                    <xs:attribute name="ApplicationName" />
+                    <xs:attribute name="ApplicationUrl" />
+                    <xs:attribute name="BootstrapperComponentFiles" />
+                    <xs:attribute name="BootstrapperItems" />
+                    <xs:attribute name="BootstrapperKeyFile" />
+                    <xs:attribute name="ComponentsLocation" />
+                    <xs:attribute name="ComponentsUrl" />
+                    <xs:attribute name="CopyComponents" />
+                    <xs:attribute name="Culture" />
+                    <xs:attribute name="FallbackCulture" />
+                    <xs:attribute name="OutputPath" />
+                    <xs:attribute name="Path" />
+                    <xs:attribute name="SupportUrl" />
+                    <xs:attribute name="Validate" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GenerateDeploymentManifest" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AssemblyName" />
+                    <xs:attribute name="AssemblyVersion" />
+                    <xs:attribute name="DeploymentUrl" />
+                    <xs:attribute name="Description" />
+                    <xs:attribute name="DisallowUrlActivation" />
+                    <xs:attribute name="EntryPoint" />
+                    <xs:attribute name="InputManifest" />
+                    <xs:attribute name="Install" />
+                    <xs:attribute name="MaxTargetPath" />
+                    <xs:attribute name="MapFileExtensions" />
+                    <xs:attribute name="MinimumRequiredVersion" />
+                    <xs:attribute name="OutputManifest" />
+                    <xs:attribute name="Platform" />
+                    <xs:attribute name="Product" />
+                    <xs:attribute name="Publisher" />
+                    <xs:attribute name="SupportUrl" />
+                    <xs:attribute name="TargetCulture" />
+                    <xs:attribute name="TrustUrlParameters" />
+                    <xs:attribute name="UpdateEnabled" />
+                    <xs:attribute name="UpdateInterval" />
+                    <xs:attribute name="UpdateMode" />
+                    <xs:attribute name="UpdateUnit" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GenerateResource" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Sources" use="required" />
+                    <xs:attribute name="FilesWritten" />
+                    <xs:attribute name="NeverLockTypeAssemblies" />
+                    <xs:attribute name="OutputResources" />
+                   <xs:attribute name="References" />
+                    <xs:attribute name="StateFile" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="UseSourcePath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GetAssemblyIdentity" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AssemblyFiles" use="required" />
+                    <xs:attribute name="Assemblies" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GetFrameworkPath" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Path" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GetFrameworkSdkPath" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Path" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GetLinkedFilesFromResX" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Sources" use="required" />
+                    <xs:attribute name="StateFile" />
+                    <xs:attribute name="UseSourcePath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="LC" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="LicenseTarget" use="required" />
+                    <xs:attribute name="Sources" use="required" />
+                    <xs:attribute name="NoLogo" />
+                    <xs:attribute name="OutputDirectory" />
+                    <xs:attribute name="OutputLicense" />
+                    <xs:attribute name="ReferencedAssemblies" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="MakeDir" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Directories" use="required" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Message" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Importance" />
+                    <xs:attribute name="Text" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="MSBuild" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Projects" use="required" />
+                    <xs:attribute name="RebaseOutputs" />
+                    <xs:attribute name="StopOnFirstFailure" />
+                    <xs:attribute name="RunEachTargetSeparately" />
+                    <xs:attribute name="Targets" />
+                    <xs:attribute name="Properties" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ReadLinesFromFile" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="File" use="required" />
+                    <xs:attribute name="Lines" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="RegisterAssembly" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Assemblies" use="required" />
+                    <xs:attribute name="CreateCodeBase" />
+                    <xs:attribute name="StateFile" />
+                    <xs:attribute name="TypeLibFiles" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="RemoveDir" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Directories" use="required" />
+                    <xs:attribute name="RemovedDirectories" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="RemoveDuplicates" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Filtered" />
+                    <xs:attribute name="Inputs" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ResGen" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Sources" use="required" />
+                    <xs:attribute name="FilesWritten" />
+                    <xs:attribute name="OutputResources" />
+                    <xs:attribute name="References" />
+                    <xs:attribute name="StateFile" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                    <xs:attribute name="UseSourcePath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ResolveAssemblyReference" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="SearchPaths" use="required" />
+                    <xs:attribute name="AppConfigFile" />
+                    <xs:attribute name="Assemblies" />
+                    <xs:attribute name="AssemblyFiles" />
+                    <xs:attribute name="AutoUnify" />
+                    <xs:attribute name="CandidateAssemblyFiles" />
+                    <xs:attribute name="FilesWritten" />
+                    <xs:attribute name="FindDependencies" />
+                    <xs:attribute name="FindRelatedFiles" />
+                    <xs:attribute name="FindSatellites" />
+                    <xs:attribute name="InstalledAssemblyTables" />
+                    <xs:attribute name="Silent" />
+                    <xs:attribute name="StateFile" />
+                    <xs:attribute name="TargetFrameworkDirectory" />
+                    <xs:attribute name="TargetProcessorArchitecture" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ResolveComReference" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="DelaySign" />
+                    <xs:attribute name="KeyContainer" />
+                    <xs:attribute name="KeyFile" />
+                    <xs:attribute name="NoClassMembers" />
+                    <xs:attribute name="ResolvedAssemblyReferences" />
+                    <xs:attribute name="ResolvedFiles" />
+                    <xs:attribute name="ResolvedModules" />
+                    <xs:attribute name="StateFile" />
+                    <xs:attribute name="TypeLibFiles" />
+                    <xs:attribute name="TypeLibNames" />
+                    <xs:attribute name="WrapperOutputDirectory" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ResolveKeySource" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AutoClosePasswordPromptShow" />
+                    <xs:attribute name="AutoClosePasswordPromptTimeout" />
+                    <xs:attribute name="CertificateFile" />
+                    <xs:attribute name="CertificateThumbprint" />
+                    <xs:attribute name="KeyFile" />
+                    <xs:attribute name="ResolvedKeyContainer" />
+                    <xs:attribute name="ResolvedKeyFile" />
+                    <xs:attribute name="ResolvedThumbprint" />
+                    <xs:attribute name="SuppressAutoClosePasswordPrompt" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="GenerateTrustInfo" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="BaseManifest" />
+                    <xs:attribute name="ExcludedPermissions" />
+                    <xs:attribute name="TargetZone" use="required" />
+                    <xs:attribute name="TrustInfoFile" use="required" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ResolveManifestFiles" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="EntryPoint" />
+                    <xs:attribute name="TrustInfoFile" />
+                    <xs:attribute name="Dependencies" /> <!-- obsolete -->
+                    <xs:attribute name="ExtraFiles" />
+                    <xs:attribute name="Files" />
+                    <xs:attribute name="ManagedAssemblies" />
+                    <xs:attribute name="NativeAssemblies" />
+                    <xs:attribute name="OutputAssemblies" />
+                    <xs:attribute name="OutputDependencies" /> <!-- obsolete -->
+                    <xs:attribute name="OutputFiles" />
+                    <xs:attribute name="OutputPrerequisites" /> <!-- obsolete -->
+                    <xs:attribute name="OutputSatellites" /> <!-- obsolete -->
+                    <xs:attribute name="PublishFiles" />
+                    <xs:attribute name="Satellites" /> <!-- obsolete -->
+                    <xs:attribute name="SatelliteAssemblies" />
+                    <xs:attribute name="TargetCulture" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ResolveNativeReference" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="NativeReferences" use="required" />
+                    <xs:attribute name="ContainedComComponents" />
+                    <xs:attribute name="ContainedLooseEtcFiles" />
+                    <xs:attribute name="ContainedLooseTlbFiles" />
+                    <xs:attribute name="ContainedNetAssemblies" />
+                    <xs:attribute name="ContainedTypeLibraries" />
+                    <xs:attribute name="ContainingReferenceFiles" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="ResolveVCProjectOutput" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="ProjectReferences" use="required" />
+                    <xs:attribute name="Configuration" />
+                    <xs:attribute name="PreresolvedVCOutputs" />
+                    <xs:attribute name="ResolvedOutputPaths" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="SGen" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="BuildAssemblyName" use="required" />
+                    <xs:attribute name="BuildAssemblyPath" use="required" />
+                    <xs:attribute name="ShouldGenerateSerializer" use="required" />
+                    <xs:attribute name="DelaySign" />
+                    <xs:attribute name="KeyContainer" />
+                    <xs:attribute name="KeyFile" />
+                    <xs:attribute name="References" />
+                    <xs:attribute name="SerializationAssembly" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="SignFile" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="CertificateThumbprint" use="required" />
+                    <xs:attribute name="SigningTarget" use="required" />
+                    <xs:attribute name="TimestampUrl" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Touch" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Files" use="required" />
+                    <xs:attribute name="AlwaysCreate" />
+                    <xs:attribute name="ForceTouch" />
+                    <xs:attribute name="Time" />
+                    <xs:attribute name="TouchedFiles" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="UnregisterAssembly" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Assemblies" />
+                    <xs:attribute name="StateFile" />
+                    <xs:attribute name="TypeLibFiles" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="UpdateManifest" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="InputManifest" use="required" />
+                    <xs:attribute name="ApplicationManifest" />
+                    <xs:attribute name="ApplicationPath" />
+                    <xs:attribute name="OutputManifest" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Vbc" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AdditionalLibPaths" />
+                    <xs:attribute name="AddModules" />
+                    <xs:attribute name="BaseAddress" />
+                    <xs:attribute name="CodePage" />
+                    <xs:attribute name="DebugType" />
+                    <xs:attribute name="DefineConstants" />
+                    <xs:attribute name="DelaySign" />
+                    <xs:attribute name="DisabledWarnings" />
+                    <xs:attribute name="DocumentationFile" />
+                    <xs:attribute name="EmitDebugInformation" />
+                    <xs:attribute name="ErrorReport" />
+                    <xs:attribute name="FileAlignment" />
+                    <xs:attribute name="GenerateDocumentation" />
+                    <xs:attribute name="Imports" />
+                    <xs:attribute name="KeyContainer" />
+                    <xs:attribute name="KeyFile" />
+                    <xs:attribute name="LinkResources" />
+                    <xs:attribute name="MainEntryPoint" />
+                    <xs:attribute name="NoConfig" />
+                    <xs:attribute name="NoLogo" />
+                    <xs:attribute name="NoStandardLib" />
+                    <xs:attribute name="NoWarnings" />
+                    <xs:attribute name="Optimize" />
+                    <xs:attribute name="OptionCompare" />
+                    <xs:attribute name="OptionExplicit" />
+                    <xs:attribute name="OptionStrict" />
+                    <xs:attribute name="OutputAssembly" />
+                    <xs:attribute name="Platform" />
+                    <xs:attribute name="References" />
+                    <xs:attribute name="RemoveIntegerChecks" />
+                    <xs:attribute name="Resources" />
+                    <xs:attribute name="ResponseFiles" />
+                    <xs:attribute name="RootNamespace" />
+                    <xs:attribute name="SdkPath" />
+                    <xs:attribute name="Sources" />
+                    <xs:attribute name="TargetCompactFramework" />
+                    <xs:attribute name="TargetType" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                    <xs:attribute name="TreatWarningsAsErrors" />
+                    <xs:attribute name="UseHostCompilerIfAvailable" />
+                    <xs:attribute name="Utf8Output" />
+                    <xs:attribute name="Verbosity" />
+                    <xs:attribute name="WarningsAsErrors" />
+                    <xs:attribute name="WarningsNotAsErrors" />
+                    <xs:attribute name="Win32Icon" />
+                    <xs:attribute name="Win32Resource" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="VCBuild" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Projects" use="required" />
+                    <xs:attribute name="Clean" />
+                    <xs:attribute name="Configuration" />
+                    <xs:attribute name="Override" />
+                    <xs:attribute name="Rebuild" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Vjc" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="AdditionalLibPaths" />
+                    <xs:attribute name="AddModules" />
+                    <xs:attribute name="BaseAddress" />
+                    <xs:attribute name="CodePage" />
+                    <xs:attribute name="DebugType" />
+                    <xs:attribute name="DefineConstants" />
+                    <xs:attribute name="DelaySign" />
+                    <xs:attribute name="DisabledWarnings" />
+                    <xs:attribute name="DisableExtensions" />
+                    <xs:attribute name="DocumentationFile" />
+                    <xs:attribute name="EmitDebugInformation" />
+                    <xs:attribute name="FileAlignment" />
+                    <xs:attribute name="Jcpa" />
+                    <xs:attribute name="KeyContainer" />
+                    <xs:attribute name="KeyFile" />
+                    <xs:attribute name="LinkResources" />
+                    <xs:attribute name="MainEntryPoint" />
+                    <xs:attribute name="NoConfig" />
+                    <xs:attribute name="NoLogo" />
+                    <xs:attribute name="Optimize" />
+                    <xs:attribute name="OutputAssembly" />
+                    <xs:attribute name="References" />
+                    <xs:attribute name="Resources" />
+                    <xs:attribute name="ResponseFiles" />
+                    <xs:attribute name="SecureScoping" />
+                    <xs:attribute name="Sources" />
+                    <xs:attribute name="TargetType" />
+                    <xs:attribute name="Timeout" />
+                    <xs:attribute name="ToolPath" />
+                    <xs:attribute name="TreatWarningsAsErrors" />
+                    <xs:attribute name="Utf8Output" />
+                    <xs:attribute name="WarningLevel" />
+                    <xs:attribute name="Win32Icon" />
+                    <xs:attribute name="Win32Resource" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="VjsResGen" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Sources" use="required" />
+                    <xs:attribute name="OutputResx" />
+                    <xs:attribute name="WildCards" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="Warning" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="Text" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+    <xs:element name="WriteLinesToFile" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="File" use="required" />
+                    <xs:attribute name="Lines" />
+                    <xs:attribute name="Overwrite" />
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>
+</xs:schema>
diff --git a/mcs/tools/xbuild/data/MSBuild/Microsoft.Build.Core.xsd b/mcs/tools/xbuild/data/MSBuild/Microsoft.Build.Core.xsd
new file mode 100644 (file)
index 0000000..c8f2aac
--- /dev/null
@@ -0,0 +1,390 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema targetNamespace="http://schemas.microsoft.com/developer/msbuild/2003" xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
+    <!-- ======================================================================================= -->
+    <xs:element name="Project">
+        <xs:complexType>
+            <xs:sequence>
+                <xs:group ref="msb:ProjectLevelTagExceptTargetOrImportType" minOccurs="0" maxOccurs="unbounded"/>
+                <!-- must be at least one Target or Import tag-->
+                <xs:group ref="msb:TargetOrImportType"/>
+                <xs:group ref="msb:ProjectLevelTagType" minOccurs="0" maxOccurs="unbounded"/>
+            </xs:sequence>
+            <xs:attribute name="DefaultTargets" type="xs:string" use="optional">
+                <xs:annotation>
+                    <xs:documentation>Optional semi-colon separated list of one or more targets that will be built if no targets are otherwise specified</xs:documentation>
+                </xs:annotation>
+            </xs:attribute>
+        </xs:complexType>
+    </xs:element>
+    <!-- ======================================================================================= -->
+    <xs:group name="ProjectLevelTagExceptTargetOrImportType">
+        <xs:choice>
+            <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
+            <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
+            <xs:element name="Choose" type="msb:ChooseType"/>
+            <xs:element name="Error" type="msb:WarningErrorOutsideTargetType">
+                <xs:annotation>
+                    <xs:documentation>Logs an Error event</xs:documentation>
+                </xs:annotation>
+            </xs:element>
+            <xs:element name="Warning" type="msb:WarningErrorOutsideTargetType">
+                <xs:annotation>
+                    <xs:documentation>Logs a Warning event</xs:documentation>
+                </xs:annotation>
+            </xs:element>
+            <xs:element name="Message" type="msb:MessageOutsideTargetType"/>
+            <xs:element name="UsingTask" type="msb:UsingTaskType"/>
+            <xs:element name="ProjectExtensions" type="msb:ProjectExtensionsType"/>
+        </xs:choice>
+    </xs:group>
+    <!-- ======================================================================================= -->
+    <xs:group name="ProjectLevelTagType">
+        <xs:choice>
+            <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
+            <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
+            <xs:element name="Choose" type="msb:ChooseType"/>
+            <xs:element name="Error" type="msb:WarningErrorOutsideTargetType">
+                <xs:annotation>
+                    <xs:documentation>Logs an Error event</xs:documentation>
+                </xs:annotation>
+            </xs:element>
+            <xs:element name="Warning" type="msb:WarningErrorOutsideTargetType">
+                <xs:annotation>
+                    <xs:documentation>Logs a Warning event</xs:documentation>
+                </xs:annotation>
+            </xs:element>
+            <xs:element name="Message" type="msb:MessageOutsideTargetType"/>
+            <xs:element name="UsingTask" type="msb:UsingTaskType"/>
+            <xs:element name="Target" type="msb:TargetType"/>
+            <xs:element name="Import" type="msb:ImportType"/>
+            <xs:element name="ProjectExtensions" type="msb:ProjectExtensionsType"/>
+        </xs:choice>
+    </xs:group>
+    <!-- ======================================================================================= -->
+    <xs:group name="TargetOrImportType">
+        <xs:choice>
+            <xs:element name="Target" type="msb:TargetType"/>
+            <xs:element name="Import" type="msb:ImportType"/>
+        </xs:choice>
+    </xs:group>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="TargetType">
+        <xs:annotation>
+            <xs:documentation>Groups tasks into a section of the build process</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+            <xs:choice minOccurs="0" maxOccurs="unbounded">
+                <xs:element ref="msb:Task"/>
+            </xs:choice>
+            <xs:element name="OnError" type="msb:OnErrorType" minOccurs="0" maxOccurs="unbounded"/>
+            <!-- no elements are allowed under Target after an OnError element-->
+        </xs:sequence>
+        <xs:attribute name="Name" type="msb:non_empty_string" use="required">
+            <xs:annotation>
+                <xs:documentation>Name of the target</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="DependsOnTargets" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional semi-colon separated list of targets that should be run before this target</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Inputs" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional semi-colon separated list of files that form inputs into this target. Their timestamps will be compared with the timestamps of files in Outputs to determine whether the Target is up to date</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Outputs" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional semi-colon separated list of files that form outputs into this target. Their timestamps will be compared with the timestamps of files in Inputs to determine whether the Target is up to date</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the Target and the targets it depends on should be run</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="PropertyGroupType">
+        <xs:annotation>
+            <xs:documentation>Groups property definitions</xs:documentation>
+        </xs:annotation>
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+            <xs:element ref="msb:Property"/>
+        </xs:sequence>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the PropertyGroup should be used</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="ItemGroupType">
+        <xs:annotation>
+            <xs:documentation>Groups item list definitions</xs:documentation>
+        </xs:annotation>
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+            <xs:element ref="msb:Item"/>
+        </xs:sequence>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the ItemGroup should be used</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="ChooseType">
+        <xs:annotation>
+            <xs:documentation>Groups When and Otherwise elements</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+            <xs:element name="When" type="msb:WhenType" maxOccurs="unbounded"/>
+            <xs:element name="Otherwise" type="msb:OtherwiseType" minOccurs="0"/>
+        </xs:sequence>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="WhenType">
+        <xs:annotation>
+            <xs:documentation>Groups PropertyGroup and/or ItemGroup elements</xs:documentation>
+        </xs:annotation>
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+            <xs:choice>
+                <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
+                <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
+                <xs:element name="Choose" type="msb:ChooseType"/>
+            </xs:choice>
+        </xs:sequence>
+        <xs:attribute name="Condition" type="xs:string" use="required">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the child PropertyGroups and/or ItemGroups should be used</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="OtherwiseType">
+        <xs:annotation>
+            <xs:documentation>Groups PropertyGroup and/or ItemGroup elements that are used if no Conditions on sibling When elements evaluate to true</xs:documentation>
+        </xs:annotation>
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+            <xs:choice>
+                <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
+                <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
+                <xs:element name="Choose" type="msb:ChooseType"/>
+            </xs:choice>
+        </xs:sequence>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="OnErrorType">
+        <xs:annotation>
+            <xs:documentation>Specifies targets to execute in the event of a recoverable error</xs:documentation>
+        </xs:annotation>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the targets should be executed</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="ExecuteTargets" type="msb:non_empty_string" use="required">
+            <xs:annotation>
+                <xs:documentation>Semi-colon separated list of targets to execute</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="MessageOutsideTargetType">
+        <xs:annotation>
+            <xs:documentation>Logs an informational Message event, with an optional Importance</xs:documentation>
+        </xs:annotation>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the Message should be logged</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Importance" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional priority level. Allowed values are Low, Normal (default), and High</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Text" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Text to log</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="WarningErrorOutsideTargetType">
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the text should be logged</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Text" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Text to log</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="UsingTaskType">
+        <xs:annotation>
+            <xs:documentation>Declares where to load a task that will be used in the project</xs:documentation>
+        </xs:annotation>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the declaration should be evaluated</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="AssemblyName" type="msb:non_empty_string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional name of assembly containing the task. Either AssemblyName or AssemblyFile must be used</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="AssemblyFile" type="msb:non_empty_string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional path to assembly containing the task. Either AssemblyName or AssemblyFile must be used</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="TaskName" type="msb:non_empty_string" use="required">
+            <xs:annotation>
+                <xs:documentation>Name of task class in the assembly</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="ImportType">
+        <xs:annotation>
+            <xs:documentation>Declares that the contents of another project file should be inserted at this location</xs:documentation>
+        </xs:annotation>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the import should occur</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Project" type="msb:non_empty_string" use="required">
+            <xs:annotation>
+                <xs:documentation>Project file to import</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="ProjectExtensionsType" mixed="true">
+        <xs:annotation>
+            <xs:documentation>Optional section used by MSBuild hosts, that may contain arbitrary XML content that is ignored by MSBuild itself</xs:documentation>
+        </xs:annotation>
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+            <xs:any processContents="skip"/>
+        </xs:sequence>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:element name="Item" type="msb:SimpleItemType" abstract="true"/>
+    <!-- ======================================================================================= -->
+    <!-- convenience type for items that have no meta-data-->
+    <xs:complexType name="SimpleItemType">
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the items should be evaluated</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Include" type="xs:string" use="required">
+            <xs:annotation>
+                <xs:documentation>Semi-colon separated list of files (wildcards are allowed) or other item names to include in this item list</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="Exclude" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Semi-colon separated list of files (wildcards are allowed) or other item names to exclude from the Include list</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <!-- general utility type allowing an item type to be defined but not its child meta-data-->
+    <xs:complexType name="GenericItemType">
+        <xs:complexContent>
+            <xs:extension base="msb:SimpleItemType">
+                <xs:sequence minOccurs="0" maxOccurs="unbounded">
+                    <xs:any namespace="##any" processContents="skip"/>
+                </xs:sequence>
+            </xs:extension>
+        </xs:complexContent>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <!-- no type declared on this abstract element, so either a simple or complex type can be substituted for it.-->
+    <xs:element name="Property" abstract="true"/>
+    <!-- ======================================================================================= -->
+    <!-- convenience type for properties that just want to allow text and no elements in them-->
+    <xs:complexType name="StringPropertyType">
+        <xs:simpleContent>
+            <xs:extension base="xs:string">
+                <xs:attribute name="Condition" type="xs:string" use="optional">
+                    <xs:annotation>
+                        <xs:documentation>Optional expression evaluated to determine whether the property should be evaluated</xs:documentation>
+                    </xs:annotation>
+                </xs:attribute>
+            </xs:extension>
+        </xs:simpleContent>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <!-- general utility type allowing text and/or elements inside-->
+    <xs:complexType name="GenericPropertyType" mixed="true">
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+            <xs:any namespace="##any" processContents="skip"/>
+        </xs:sequence>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the property should be evaluated</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <xs:element name="Task" type="msb:TaskType" abstract="true"/>
+    <!-- ======================================================================================= -->
+    <xs:complexType name="TaskType">
+        <xs:sequence minOccurs="0" maxOccurs="unbounded">
+            <xs:element name="Output">
+                <xs:annotation>
+                    <xs:documentation>Optional element specifying a specific task output to be gathered</xs:documentation>
+                </xs:annotation>
+                <xs:complexType>
+                    <xs:attribute name="TaskParameter" type="msb:non_empty_string" use="required">
+                        <xs:annotation>
+                            <xs:documentation>Task parameter to gather. Matches the name of a .NET Property on the task class that has an [Output] attribute</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                    <xs:attribute name="ItemName" type="msb:non_empty_string" use="optional">
+                        <xs:annotation>
+                            <xs:documentation>Optional name of an item list to put the gathered outputs into. Either ItemName or PropertyName must be specified</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                    <xs:attribute name="PropertyName" type="msb:non_empty_string" use="optional">
+                        <xs:annotation>
+                            <xs:documentation>Optional name of a property to put the gathered output into. Either PropertyName or ItemName must be specified</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                    <xs:attribute name="Condition" type="xs:string" use="optional">
+                        <xs:annotation>
+                            <xs:documentation>Optional expression evaluated to determine whether the output should be gathered</xs:documentation>
+                        </xs:annotation>
+                    </xs:attribute>
+                </xs:complexType>
+            </xs:element>
+        </xs:sequence>
+        <xs:attribute name="Condition" type="xs:string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional expression evaluated to determine whether the task should be executed</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <xs:attribute name="ContinueOnError" type="msb:non_empty_string" use="optional">
+            <xs:annotation>
+                <xs:documentation>Optional boolean indicating whether a recoverable task error should be ignored. Default false</xs:documentation>
+            </xs:annotation>
+        </xs:attribute>
+        <!-- We don't need the anyAttribute here because other types deriving from this type will add the right attributes.-->
+    </xs:complexType>
+    <!-- ======================================================================================= -->
+    <!-- XSD considers an empty-valued attribute to satisfy use="required", but we want it to have a non-empty value in most cases, hence this utility type. -->
+    <xs:simpleType name="non_empty_string">
+        <xs:restriction base="xs:string">
+            <xs:minLength value="1"/>
+        </xs:restriction>
+    </xs:simpleType>
+</xs:schema>
diff --git a/mcs/tools/xbuild/data/Microsoft.Build.xsd b/mcs/tools/xbuild/data/Microsoft.Build.xsd
new file mode 100644 (file)
index 0000000..e88f00f
--- /dev/null
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xs:schema targetNamespace="http://schemas.microsoft.com/developer/msbuild/2003"
+xmlns:xs="http://www.w3.org/2001/XMLSchema"
+xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003"
+elementFormDefault="qualified">
+
+    <!-- =================== IMPORT COMMON SCHEMA =========================== -->
+    <xs:include schemaLocation="MSBuild/Microsoft.Build.CommonTypes.xsd"/>
+
+    <!-- ========= ADD CUSTOM ITEMS, PROPERTIES, AND TASKS BELOW ======= -->
+    <!-- Note that these will be in the msbuild namespace. A future version of
+        msbuild may require that custom itemtypes, properties, and tasks be in a
+        custom namespace, but currently msbuild only supports the msbuild namespace. -->
+
+    <!-- example custom itemtype with particular meta-data required-->
+    <!--<xs:element name="MyItem" substitutionGroup="msb:Item">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:SimpleItemType">
+                    <xs:sequence maxOccurs="1">
+                        <xs:choice>
+                            <xs:element name="MyMetaData" type="xs:string"/>
+                        </xs:choice>
+                    </xs:sequence>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>-->
+
+    <!-- Example custom itemtype with NO meta-data -->
+    <!--<xs:element name="MySimpleItem" type="msb:SimpleItemType" substitutionGroup="msb:Item"/>-->
+
+    <!-- Example custom itemtype with ANY meta-data -->
+    <!--<xs:element name="MyFlexibleItem" type="msb:GenericItemType" substitutionGroup="msb:Item"/>-->
+
+    <!-- example custom property that allows string content only-->
+    <!--<xs:element name="MySimpleProperty" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>-->
+
+    <!-- example custom task with single required parameter-->
+    <!--<xs:element name="MyTask" substitutionGroup="msb:Task">
+        <xs:complexType>
+            <xs:complexContent>
+                <xs:extension base="msb:TaskType">
+                    <xs:attribute name="MyParameter" type="xs:boolean" use="required"/>
+                </xs:extension>
+            </xs:complexContent>
+        </xs:complexType>
+    </xs:element>-->
+
+</xs:schema>
diff --git a/mcs/tools/xbuild/data/Microsoft.CSharp.targets b/mcs/tools/xbuild/data/Microsoft.CSharp.targets
new file mode 100644 (file)
index 0000000..c23b8ae
--- /dev/null
@@ -0,0 +1,118 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <PropertyGroup>
+               <DefaultLanguageSourceExtension>.cs</DefaultLanguageSourceExtension>
+               <Language>C#</Language>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <DebugSymbols Condition=" '$(DebugType)' == 'none' ">false</DebugSymbols>
+               <DebugType    Condition=" '$(DebugType)' == 'none' "></DebugType>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <CreateManifestResourceNamesDependsOn></CreateManifestResourceNamesDependsOn>
+               <CoreCompileDependsOn></CoreCompileDependsOn>
+
+               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildToolsPath)\Microsoft.CSharp.targets</MSBuildAllProjects>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <DocFileItem Include="$(DocumentationFile)" Condition="'$(DocumentationFile)' != ''"/>
+       </ItemGroup>
+
+       <Target
+               Name="CoreCompile"
+               Inputs="$(MSBuildAllProjects);@(Compile);@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile);
+                       $(KeyOriginatorFile);@(ReferencePath);$(Win32Icon);$(Win32Resource)"
+               Outputs="@(DocFileItem);@(IntermediateAssembly)"
+               DependsOnTargets="$(CoreCompileDependsOn)"
+       >
+               <Csc
+                       AdditionalLibPaths="$(AdditionalLibPaths)"
+                       AddModules="@(AddModules)"
+                       AllowUnsafeBlocks="$(AllowUnsafeBlocks)"
+                       BaseAddress="$(BaseAddress)"
+                       CheckForOverflowUnderflow="$(CheckForOverflowUnderflow)"
+                       CodePage="$(CodePage)"
+                       DebugType="$(DebugType)"
+                       DefineConstants="$(DefineConstants)"
+                       DelaySign="$(DelaySign)"
+                       DisabledWarnings="$(NoWarn)"
+                       DocumentationFile="@(DocFileItem)"
+                       EmitDebugInformation="$(DebugSymbols)"
+                       ErrorReport="$(ErrorReport)"
+                       FileAlignment="$(FileAlignment)"
+                       GenerateFullPaths="$(GenerateFullPaths)"
+                       KeyContainer="$(KeyContainerName)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       LangVersion="$(LangVersion)"
+                       MainEntryPoint="$(StartupObject)"
+                       ModuleAssemblyName="$(ModuleAssemblyName)"
+                       NoConfig="true"
+                       NoLogo="$(NoLogo)"
+                       NoStandardLib="$(NoStdLib)"
+                       Optimize="$(Optimize)"
+                       OutputAssembly="@(IntermediateAssembly)"
+                       PdbFile="$(PdbFile)"
+                       Platform="$(PlatformTarget)"
+                       References="@(ReferencePath)"
+                       ResponseFiles="$(CompilerResponseFile)"
+                       Sources="@(Compile)"
+                       TargetType="$(OutputType)"
+                       TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
+                       UseHostCompilerIfAvailable="$(UseHostCompilerIfAvailable)"
+                       Utf8Output="$(Utf8Output)"
+                       WarningLevel="$(WarningLevel)"
+                       WarningsAsErrors="$(WarningsAsErrors)"
+                       WarningsNotAsErrors="$(WarningsNotAsErrors)"
+                       Win32Icon="$(Win32Icon)"
+                       Win32Resource="$(Win32Resource)"
+                       Resources="@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile)"
+                       ToolExe="$(CscToolExe)"
+                       ToolPath="$(CscToolPath)" />
+
+       </Target>
+
+       <Target Name="CreateManifestResourceNames">
+               <CreateCSharpManifestResourceName Condition="'@(ResxWithNoCulture)' != ''"
+                       ResourceFiles="@(ResxWithNoCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithNoCultureName" />
+               </CreateCSharpManifestResourceName>
+
+               <CreateCSharpManifestResourceName Condition="'@(NonResxWithNoCulture)' != ''"
+                       ResourceFiles="@(NonResxWithNoCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithNoCulture" />
+               </CreateCSharpManifestResourceName>
+
+               <CreateCSharpManifestResourceName Condition="'@(ResxWithCulture)' != ''"
+                       ResourceFiles="@(ResxWithCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithCultureName" />
+               </CreateCSharpManifestResourceName>
+
+               <CreateCSharpManifestResourceName Condition="'@(NonResxWithCulture)' != ''"
+                       ResourceFiles="@(NonResxWithCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithCulture" />
+               </CreateCSharpManifestResourceName>
+       </Target>
+
+       <Import Project="Microsoft.Common.targets" />
+
+       <PropertyGroup>
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v4.5' and '$(OS)' != 'Windows_NT'">gmcs</CscToolExe>
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v4.5' and '$(OS)' == 'Windows_NT'">gmcs.bat</CscToolExe>
+
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.5' and '$(OS)' != 'Windows_NT'">mcs</CscToolExe>
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.5' and '$(OS)' == 'Windows_NT'">mcs.bat</CscToolExe>
+
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' != 'Windows_NT'">dmcs</CscToolExe>
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' == 'Windows_NT'">dmcs.bat</CscToolExe>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <TargetFrameworkMonikerAssemblyAttributeText Condition="'$(TargetFrameworkMoniker)' != '' and '$(TargetingClr2Framework)' != 'true'">
+// &lt;autogenerated /&gt;
+[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(&quot;$(TargetFrameworkMoniker)&quot;, FrameworkDisplayName = &quot;$(TargetFrameworkMonikerDisplayName)&quot;)]
+               </TargetFrameworkMonikerAssemblyAttributeText>
+       </PropertyGroup>
+
+</Project>
diff --git a/mcs/tools/xbuild/data/Microsoft.VisualBasic.targets b/mcs/tools/xbuild/data/Microsoft.VisualBasic.targets
new file mode 100644 (file)
index 0000000..aba4cfa
--- /dev/null
@@ -0,0 +1,123 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateVisualBasicManifestResourceName" AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
+       <PropertyGroup>
+               <DefaultLanguageSourceExtension>.vb</DefaultLanguageSourceExtension>
+               <Language>VB</Language>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <CreateManifestResourceNamesDependsOn></CreateManifestResourceNamesDependsOn>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <FinalDefineConstants>CONFIG=&quot;$(Configuration)&quot;</FinalDefineConstants>
+               <FinalDefineConstants Condition=" '$(DefineDebug)' == 'true' ">$(FinalDefineConstants),DEBUG=-1</FinalDefineConstants>
+               <FinalDefineConstants Condition=" '$(DefineTrace)' == 'true' ">$(FinalDefineConstants),TRACE=-1</FinalDefineConstants>
+               <FinalDefineConstants Condition=" '$(MyType)' != '' ">$(FinalDefineConstants),_MyType=&quot;$(MyType)&quot;</FinalDefineConstants>
+               <FinalDefineConstants Condition=" '$(Platform)' != '' ">$(FinalDefineConstants),PLATFORM=&quot;$(Platform)&quot;</FinalDefineConstants>
+               <FinalDefineConstants Condition=" '$(Platform)' == '' ">$(FinalDefineConstants),PLATFORM=&quot;AnyCPU&quot;</FinalDefineConstants>
+               <FinalDefineConstants Condition=" '$(DefineConstants)' != '' ">$(FinalDefineConstants),$(DefineConstants)</FinalDefineConstants>
+
+               <_NoWarnings Condition=" '$(WarningLevel)' == '0' ">true</_NoWarnings>
+               <_NoWarnings Condition=" '$(WarningLevel)' == '1' ">false</_NoWarnings>
+
+               <DebugSymbols Condition=" '$(DebugType)' == 'none' ">false</DebugSymbols>
+               <DebugType    Condition=" '$(DebugType)' == 'none' "></DebugType>
+
+               <CoreCompileDependsOn></CoreCompileDependsOn>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <DocFileItem Include="$(DocumentationFile)"  Condition="'$(DocumentationFile)'!=''"/>
+       </ItemGroup>
+
+       <Target
+               Name="CoreCompile"
+               Inputs="$(MSBuildAllProjects);@(Compile);@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile);@(DocFileItem);
+                       $(KeyOriginatorFile);@(ReferencePath);$(Win32Icon);$(Win32Resource)"
+               Outputs="@(IntermediateAssembly)"
+               DependsOnTargets="$(CoreCompileDependsOn)"
+       >
+               <Vbc
+                       AdditionalLibPaths="$(AdditionalLibPaths)"
+                       AddModules="@(AddModules)"
+                       BaseAddress="$(BaseAddress)"
+                       CodePage="$(CodePage)"
+                       DebugType="$(DebugType)"
+                       DefineConstants="$(FinalDefineConstants)"
+                       DelaySign="$(DelaySign)"
+                       DisabledWarnings="$(NoWarn)"
+                       DocumentationFile="@(DocFileItem)"
+                       EmitDebugInformation="$(DebugSymbols)"
+                       ErrorReport="$(ErrorReport)"
+                       FileAlignment="$(FileAlignment)"
+                       GenerateDocumentation="$(GenerateDocumentation)"
+                       Imports="@(Import)"
+                       KeyContainer="$(KeyContainerName)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       MainEntryPoint="$(StartupObject)"
+                       NoConfig="true"
+                       NoLogo="$(NoLogo)"
+                       NoStandardLib="$(NoStdLib)"
+                       NoWarnings="$(_NoWarnings)"
+                       Optimize="$(Optimize)"
+                       OptionCompare="$(OptionCompare)"
+                       OptionExplicit="$(OptionExplicit)"
+                       OptionStrict="$(OptionStrict)"
+                       OptionStrictType="$(OptionStrictType)"
+                       OutputAssembly="@(IntermediateAssembly)"
+                       Platform="$(PlatformTarget)"
+                       References="@(ResolvedFiles)"
+                       RemoveIntegerChecks="$(RemoveIntegerChecks)"
+                       Resources="@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile)"
+                       ResponseFiles="$(CompilerResponseFile)"
+                       RootNamespace="$(RootNamespace)"
+                       Sources="@(Compile)"
+                       TargetType="$(OutputType)"
+                       TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
+                       UseHostCompilerIfAvailable="$(UseHostCompilerIfAvailable)"
+                       Utf8Output="$(Utf8Output)"
+                       Verbosity="$(VbcVerbosity)"
+                       WarningsAsErrors="$(WarningsAsErrors)"
+                       WarningsNotAsErrors="$(WarningsNotAsErrors)"
+                       Win32Icon="$(Win32Icon)"
+                       Win32Resource="$(Win32Resource)"
+                       ToolExe="$(VbcToolExe)"
+                       ToolPath="$(VbcToolPath)"
+                       />
+
+       </Target>
+
+       <Target Name="CreateManifestResourceNames">
+               <CreateVisualBasicManifestResourceName Condition="'@(ResxWithNoCulture)' != ''"
+                       ResourceFiles="@(ResxWithNoCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithNoCultureName" />
+               </CreateVisualBasicManifestResourceName>
+
+               <CreateVisualBasicManifestResourceName Condition="'@(NonResxWithNoCulture)' != ''"
+                       ResourceFiles="@(NonResxWithNoCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithNoCulture" />
+               </CreateVisualBasicManifestResourceName>
+
+               <CreateVisualBasicManifestResourceName Condition="'@(ResxWithCulture)' != ''"
+                       ResourceFiles="@(ResxWithCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithCultureName" />
+               </CreateVisualBasicManifestResourceName>
+
+               <CreateVisualBasicManifestResourceName Condition="'@(NonResxWithCulture)' != ''"
+                       ResourceFiles="@(NonResxWithCulture)" RootNamespace="$(RootNamespace)">
+                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithCulture" />
+               </CreateVisualBasicManifestResourceName>
+       </Target>
+
+       <Import Project="Microsoft.Common.targets" />
+
+       <PropertyGroup>
+               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' != 'Windows_NT'">vbnc2</VbcToolExe>
+               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' == 'Windows_NT'">vbnc2.bat</VbcToolExe>
+
+               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' != 'Windows_NT'">vbnc</VbcToolExe>
+               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' == 'Windows_NT'">vbnc.bat</VbcToolExe>
+       </PropertyGroup>
+
+</Project>
diff --git a/mcs/tools/xbuild/data/xbuild.exe.config.in b/mcs/tools/xbuild/data/xbuild.exe.config.in
new file mode 100644 (file)
index 0000000..8127938
--- /dev/null
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+       <runtime>
+               <generatePublisherEvidence enabled="false" />
+               <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+                       <dependentAssembly>
+                               <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+                               <bindingRedirect oldVersion="0.0.0.0-100.0.0.0" newVersion="@ASM_VERSION@" />
+                       </dependentAssembly>
+                       <dependentAssembly>
+                               <assemblyIdentity name="Microsoft.Build.Engine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+                               <bindingRedirect oldVersion="0.0.0.0-100.0.0.0" newVersion="@ASM_VERSION@" />
+                       </dependentAssembly>
+               </assemblyBinding>
+       </runtime>
+</configuration>
diff --git a/mcs/tools/xbuild/data/xbuild.rsp b/mcs/tools/xbuild/data/xbuild.rsp
new file mode 100644 (file)
index 0000000..9b9ce70
--- /dev/null
@@ -0,0 +1,3 @@
+# xbuild command line options specified here will be used
+# by xbuild on every build, unless /noautoresponse is passed
+# on the command line.
diff --git a/mcs/tools/xbuild/frameworks/net_2.0.xml b/mcs/tools/xbuild/frameworks/net_2.0.xml
new file mode 100644 (file)
index 0000000..2b8bd9b
--- /dev/null
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FileList Name=".NET Framework 2.0" TargetFrameworkDirectory="..\..\..\..\2.0">
+</FileList>
diff --git a/mcs/tools/xbuild/frameworks/net_3.0.xml b/mcs/tools/xbuild/frameworks/net_3.0.xml
new file mode 100644 (file)
index 0000000..ae06c88
--- /dev/null
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FileList Name=".NET Framework 3.0" TargetFrameworkDirectory="..\..\..\..\2.0">
+</FileList>
diff --git a/mcs/tools/xbuild/frameworks/net_3.5.xml b/mcs/tools/xbuild/frameworks/net_3.5.xml
new file mode 100644 (file)
index 0000000..1225842
--- /dev/null
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FileList  Name=".NET Framework 3.5" TargetFrameworkDirectory="..\..\..\..\3.5" IncludeFramework="v3.0">
+</FileList>
diff --git a/mcs/tools/xbuild/frameworks/net_4.0.xml b/mcs/tools/xbuild/frameworks/net_4.0.xml
new file mode 100644 (file)
index 0000000..7012794
--- /dev/null
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FileList  Name=".NET Framework 4" TargetFrameworkDirectory="..\..\..\..\4.0">
+</FileList>
diff --git a/mcs/tools/xbuild/frameworks/net_4.0_client.xml b/mcs/tools/xbuild/frameworks/net_4.0_client.xml
new file mode 100644 (file)
index 0000000..951933a
--- /dev/null
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FileList Name=".NET Framework 4 Client Profile" TargetFrameworkDirectory="..\..\..\..\..\..\4.0">
+  <File AssemblyName="System" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Activities" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.Dynamic" Version="4.0.0.0" PublicKeyToken="b03f5f7f11d50a3a" />
+  <File AssemblyName="System.ServiceModel.Activities" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.ServiceModel.Channels" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.ServiceModel.Discovery" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.ServiceModel.Routing" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.Windows.Forms.DataVisualization" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.Xaml" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Core" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.AddIn" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.ComponentModel.Composition" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.ComponentModel.DataAnnotations" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.Data.DataSetExtensions" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Data.Entity" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Data.Linq" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Data.Services.Client" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.DirectoryServices.AccountManagement" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Management.Instrumentation" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Net" Version="4.0.0.0" PublicKeyToken="b03f5f7f11d50a3a" />
+  <File AssemblyName="System.Numerics" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Web.ApplicationServices" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.Windows.Presentation" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Xml.Linq" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="PresentationCore" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="PresentationFramework.Aero" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="PresentationFramework.Classic" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="PresentationFramework" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="PresentationFramework.Luna" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="PresentationFramework.Royale" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="ReachFramework" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.IdentityModel" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.IdentityModel.Selectors" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.IO.Log" Version="4.0.0.0" PublicKeyToken="b03f5f7f11d50a3a" />
+  <File AssemblyName="System.Printing" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.Runtime.Serialization" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Runtime.DurableInstancing" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.ServiceModel" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="UIAutomationClient" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="UIAutomationClientsideProviders" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="UIAutomationProvider" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="UIAutomationTypes" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="WindowsBase" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="WindowsFormsIntegration" Version="4.0.0.0" PublicKeyToken="31bf3856ad364e35" />
+  <File AssemblyName="System.Configuration" Version="4.0.0.0" PublicKeyToken="b03f5f7f11d50a3a" />
+  <File AssemblyName="System.Data.SqlXml" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="System.Deployment" Version="4.0.0.0" PublicKeyToken="b03f5f7f11d50a3a" />
+  <File AssemblyName="System.DirectoryServices.Protocols" Version="4.0.0.0" PublicKeyToken="b03f5f7f11d50a3a" />
+  <File AssemblyName="System.Transactions" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+  <File AssemblyName="mscorlib" Version="4.0.0.0" PublicKeyToken="b77a5c561934e089" />
+</FileList>
diff --git a/mcs/tools/xbuild/frameworks/net_4.5.xml b/mcs/tools/xbuild/frameworks/net_4.5.xml
new file mode 100644 (file)
index 0000000..2fa28c4
--- /dev/null
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="utf-8"?>
+<FileList  Name=".NET Framework 4.5" TargetFrameworkDirectory="..\..\..\..\4.5">
+</FileList>
diff --git a/mcs/tools/xbuild/targets/Microsoft.Portable.CSharp_4.0.targets b/mcs/tools/xbuild/targets/Microsoft.Portable.CSharp_4.0.targets
new file mode 100644 (file)
index 0000000..d90ae2c
--- /dev/null
@@ -0,0 +1,43 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+       <PropertyGroup>
+               <AvailablePlatforms>Any CPU</AvailablePlatforms>
+
+               <TargetPlatformIdentifier>Portable</TargetPlatformIdentifier>
+               <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
+               <TargetFrameworkMonikerDisplayName>.NET Portable Subset</TargetFrameworkMonikerDisplayName>
+
+               <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
+               <NoStdLib>true</NoStdLib>
+
+               <ImplicitlyExpandTargetFramework Condition="'$(ImplicitlyExpandTargetFramework)' == '' ">true</ImplicitlyExpandTargetFramework>
+       </PropertyGroup>
+
+       <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.Targets" />
+
+       <PropertyGroup>
+               <ResolveReferencesDependsOn>
+                       $(ResolveReferencesDependsOn);
+                       ImplicitlyExpandTargetFramework;
+               </ResolveReferencesDependsOn>
+
+               <ImplicitlyExpandTargetFrameworkDependsOn>
+                       $(ImplicitlyExpandTargetFrameworkDependsOn);
+                       GetReferenceAssemblyPaths
+               </ImplicitlyExpandTargetFrameworkDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ImplicitlyExpandTargetFramework"
+               DependsOnTargets="$(ImplicitlyExpandTargetFrameworkDependsOn)">
+
+               <ItemGroup>
+                       <ReferenceAssemblyPaths Include="$(_TargetFrameworkDirectories)"/>
+                       <ReferencePath Include="%(ReferenceAssemblyPaths.Identity)\*.dll">
+                               <CopyLocal>false</CopyLocal>
+                               <ResolvedFrom>ImplicitlyExpandTargetFramework</ResolvedFrom>
+                               <IsSystemReference>True</IsSystemReference>
+                       </ReferencePath>
+               </ItemGroup>
+       </Target>
+
+</Project>
diff --git a/mcs/tools/xbuild/targets/Microsoft.Portable.CSharp_4.5.targets b/mcs/tools/xbuild/targets/Microsoft.Portable.CSharp_4.5.targets
new file mode 100644 (file)
index 0000000..e2116bf
--- /dev/null
@@ -0,0 +1,3 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <Import Project="$(MSBuildToolsPath)\Microsoft.Portable.CSharp.Targets" />
+</Project>
diff --git a/mcs/tools/xbuild/targets/Microsoft.WebApplication.targets b/mcs/tools/xbuild/targets/Microsoft.WebApplication.targets
new file mode 100644 (file)
index 0000000..0f61904
--- /dev/null
@@ -0,0 +1,31 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <PropertyGroup>
+               <WebApplicationOutputDir Condition="'$(OutDir)' != '$(OutputPath)'">$(OutDir)_PublishedWebsites\$(MSBuildProjectName)</WebApplicationOutputDir>
+
+               <PrepareForRunDependsOn>
+                       $(PrepareForRunDependsOn);
+                       _CopyWebApplication
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+
+       <!-- OutDir has been overridden, so copy all the relevant files to that -->
+       <Target Name="_CopyWebApplication" Condition="'$(OutDir)' != '$(OutputPath)'">
+               <MakeDir Directories="$(WebApplicationOutputDir)\bin"/>
+               <Copy SourceFiles="@(IntermediateAssembly)" DestinationFolder="$(WebApplicationOutputDir)\bin" SkipUnchangedFiles="true"/>
+               <Copy
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(WebApplicationOutputDir)\bin"
+                       SkipUnchangedFiles="true" />
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(WebApplicationOutputDir)\bin\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="true" />
+
+               <!-- Copy the referenced assemblies -->
+               <Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(WebApplicationOutputDir)\bin" SkipUnchangedFiles="true" />
+               <Copy SourceFiles="@(Content)" DestinationFolder="$(WebApplicationOutputDir)\%(Content.RelativeDir)" />
+       </Target>
+</Project>
index bfb39197517bdfec07172c167f7085fa7fa8dcaf..8401c09aaedd65fc1b68ec85c262426f67bd8129 100644 (file)
@@ -1,6 +1,7 @@
 ../../build/common/Consts.cs
 ../../class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/UnknownToolsVersionException.cs
 ../../class/Microsoft.Build.Framework/Mono.XBuild.Framework/AssemblyLoadInfo.cs
+XBuildConsts.cs
 AssemblyInfo.cs
 CommandLineException.cs
 ErrorUtilities.cs
diff --git a/mcs/tools/xbuild/xbuild.make b/mcs/tools/xbuild/xbuild.make
new file mode 100644 (file)
index 0000000..7cb5065
--- /dev/null
@@ -0,0 +1,25 @@
+ifneq (2.0, $(XBUILD_VERSION))
+NAME_SUFFIX = .v$(XBUILD_VERSION)
+endif
+
+XBUILD_FRAMEWORK := $(topdir)/class/lib/$(PROFILE)/Microsoft.Build.Framework.dll
+XBUILD_ENGINE := $(topdir)/class/lib/$(PROFILE)/Microsoft.Build.Engine.dll
+XBUILD_UTILITIES := $(topdir)/class/lib/$(PROFILE)/Microsoft.Build.Utilities$(NAME_SUFFIX).dll
+XBUILD_TASKS := $(topdir)/class/lib/$(PROFILE)/Mono.XBuild.Tasks.dll
+
+XBUILD_ASSEMBLY_VERSION = $(XBUILD_VERSION).0.0
+
+XBUILD_BIN_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)
+
+ifneq (2.0, $(XBUILD_VERSION))
+ifneq (3.5, $(XBUILD_VERSION))
+ifneq (4.0, $(XBUILD_VERSION))
+
+XBUILD_BIN_DIR = $(mono_libdir)/mono/xbuild/$(XBUILD_VERSION)/bin
+
+PROGRAM_INSTALL_DIR = $(XBUILD_BIN_DIR)
+LIBRARY_PACKAGE = xbuild/$(XBUILD_VERSION)/bin
+
+endif
+endif
+endif
diff --git a/mcs/tools/xbuild/xbuild/2.0/FrameworkList.xml b/mcs/tools/xbuild/xbuild/2.0/FrameworkList.xml
deleted file mode 100644 (file)
index 2b8bd9b..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<FileList Name=".NET Framework 2.0" TargetFrameworkDirectory="..\..\..\..\2.0">
-</FileList>
diff --git a/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets
deleted file mode 100644 (file)
index 9ba7f3a..0000000
+++ /dev/null
@@ -1,771 +0,0 @@
-<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-
-       <Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')"/>
-       
-       <PropertyGroup>
-               <OutputType Condition="'$(OutputType)' == ''">Exe</OutputType>
-               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <AssemblyName Condition="'$(AssemblyName)' == ''">$(MSBuildProjectName)</AssemblyName>
-               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
-               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
-               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
-               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
-               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
-
-               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
-               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
-
-               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
-               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <SkipCopyUnchangedFiles Condition="'$(SkipCopyUnchangedFiles)' == ''">true</SkipCopyUnchangedFiles>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
-               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' != '' and !HasTrailingSlash('$(BaseIntermediateOutputPath)')">$(BaseIntermediateOutputPath)\</BaseIntermediateOutputPath>
-               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
-       </PropertyGroup>
-
-       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
-               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
-               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <IntermediateOutputPath Condition="'$(IntermediateOutputPath)' != '' and !HasTrailingSlash('$(IntermediateOutputPath)')">$(IntermediateOutputPath)\</IntermediateOutputPath>
-       </PropertyGroup>
-
-       <ItemGroup>
-               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
-
-               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
-               <_OutDirItem Include="$(OutDir)"/>
-       </ItemGroup>
-
-       <PropertyGroup>
-               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
-               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
-               <TargetDir Condition=" '$(TargetDir)' == '' ">@(_OutDirItem->'%(FullPath)')</TargetDir>
-               <TargetPath Condition=" '$(TargetPath)' == '' ">@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
-               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets</MSBuildAllProjects>
-
-               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
-       </PropertyGroup>
-
-       <Target Name="_ValidateEssentialProperties">
-               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <!-- If OutDir is specified via the command line, then the earlier check
-                    to add a trailing slash won't have any affect, so error here. -->
-               <Error
-                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
-                       Text="OutDir property must end with a slash."/>
-       </Target>
-
-       <Target Name="PrepareForBuild">
-               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
-
-               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
-                    @(None) and @(Content) -->
-               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
-                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
-                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
-               </CreateItem>
-
-               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
-                       Condition="'$(AppConfig)' == ''">
-                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
-               </FindAppConfigFile>
-
-               <MakeDir 
-                       Directories="$(OutDir);$(IntermediateOutputPath);@(DocFileItem->'%(RelativeDir)')"
-               />
-       </Target>
-
-       <PropertyGroup>
-               <GetFrameworkPathsDependsOn />
-       </PropertyGroup>
-       <Target Name="GetFrameworkPaths" DependsOnTargets="$(GetFrameworkPathsDependsOn)">
-               <GetFrameworkPath>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
-                               TaskParameter="FrameworkVersion35Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion30Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion20Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-               </GetFrameworkPath>
-               <CreateProperty Value="@(_CombinedTargetFrameworkDirectoriesItem)">
-                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
-               </CreateProperty>
-
-               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
-                       Condition="'$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
-       </Target>
-
-       <PropertyGroup>
-               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
-                       .exe;
-                       .dll
-               </AllowedReferenceAssemblyFileExtensions>
-
-               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
-                       .exe.mdb;
-                       .dll.mdb;
-                       .xml
-               </AllowedReferenceRelatedFileExtensions>
-
-               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
-                       {CandidateAssemblyFiles};
-                       $(ReferencePath);
-                       @(AdditionalReferencePath);
-                       {HintPathFromItem};
-                       {TargetFrameworkDirectory};
-                       {PkgConfig};
-                       {GAC};
-                       {RawFileName};
-                       $(OutDir)
-               </AssemblySearchPaths>
-
-               <ResolveReferencesDependsOn>
-                       BeforeResolveReferences;
-                       ResolveProjectReferences;
-                       ResolveAssemblyReferences;
-                       AfterResolveReferences
-               </ResolveReferencesDependsOn>
-
-               <ResolveAssemblyReferencesDependsOn>
-                       GetFrameworkPaths;
-                       PrepareForBuild
-               </ResolveAssemblyReferencesDependsOn>
-       </PropertyGroup>
-
-       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
-
-       <Target Name="BeforeResolveReferences" />
-       <Target Name="AfterResolveReferences" />
-
-       <Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
-               <ResolveAssemblyReference
-                       Assemblies="@(Reference)"
-                       AssemblyFiles="@(ChildProjectReferences)"
-                       SearchPaths="$(AssemblySearchPaths)"
-                       CandidateAssemblyFiles="@(Content);@(None)"
-                       TargetFrameworkDirectories="$(TargetFrameworkDirectory)"
-                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
-                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
-                       FindDependencies="true"
-                       FindSatellites="true"
-                       FindRelatedFiles="true"
-               >
-                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
-                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
-                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
-                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
-                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
-                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
-               </ResolveAssemblyReference>
-       </Target>
-
-       <Target
-               Name="AssignProjectConfiguration"
-               Condition="'@(ProjectReference)' != ''">
-
-               <!-- assign configs if building a solution file -->
-               <AssignProjectConfiguration
-                       ProjectReferences = "@(ProjectReference)"
-                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
-                       Condition="'$(BuildingSolutionFile)' == 'true'">
-
-                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
-               </AssignProjectConfiguration>
-
-               <!-- Else, just -->
-               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Split projects into 2 lists
-               ProjectReferenceWithConfigurationExistent: Projects existent on disk
-               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
-
-       <Target Name="SplitProjectReferencesByExistent"
-               DependsOnTargets="AssignProjectConfiguration">
-
-               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
-                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
-                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-               </CreateItem>
-       </Target>
-
-       <Target
-               Name="ResolveProjectReferences"
-               DependsOnTargets="SplitProjectReferencesByExistent"
-       >
-               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
-                    been built, so just get the target paths -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetTargetPath"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <!-- Building a project directly, build the referenced the projects also -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
-                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
-       </Target>
-
-       <Target Name = "CopyFilesMarkedCopyLocal">
-               <Copy
-                       SourceFiles="@(ReferenceCopyLocalPaths)"
-                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWritesShareable"/>
-               </Copy>
-       </Target>
-
-<!--
-       Not needed at the moment
-       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
-               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
-                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
-               </CreateProperty>
-       </Target>
--->
-
-       <PropertyGroup>
-               <BuildDependsOn>
-                       BeforeBuild;
-                       CoreBuild;
-                       AfterBuild
-               </BuildDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeBuild"/>
-       <Target Name="AfterBuild"/>
-
-       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
-
-       <PropertyGroup>
-               <CoreBuildDependsOn>
-                       PrepareForBuild;
-                       GetFrameworkPaths;
-                       PreBuildEvent;
-                       ResolveReferences;
-                       CopyFilesMarkedCopyLocal;
-                       PrepareResources;
-                       Compile;
-                       PrepareForRun;
-                       DeployOutputFiles;
-                       _RecordCleanFile;
-                       PostBuildEvent
-               </CoreBuildDependsOn>
-       </PropertyGroup>
-
-       <Target
-               Name="CoreBuild"
-               DependsOnTargets="$(CoreBuildDependsOn)"
-               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
-
-               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
-                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
-
-               <OnError ExecuteTargets="_RecordCleanFile" />
-       </Target>
-
-       <PropertyGroup>
-               <CompileDependsOn>
-                       ResolveReferences;
-                       BeforeCompile;
-                       _TimestampBeforeCompile;
-                       CoreCompile;
-                       _TimestampAfterCompile;
-                       AfterCompile
-               </CompileDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeCompile" />
-       <Target Name="AfterCompile" />
-
-       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
-
-       <PropertyGroup>
-               <PrepareForRunDependsOn>
-                       DeployOutputFiles
-               </PrepareForRunDependsOn>
-       </PropertyGroup>
-       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
-
-       <PropertyGroup>
-               <PrepareResourcesDependsOn>
-                       AssignTargetPaths;
-                       SplitResourcesByCulture;
-                       CreateManifestResourceNames;
-                       CopyNonResxEmbeddedResources;
-                       GenerateResources;
-                       GenerateSatelliteAssemblies;
-                       CompileLicxFiles
-               </PrepareResourcesDependsOn>
-       </PropertyGroup>
-       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
-
-       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
-               <!-- Extract .licx files into @(LicxFiles) -->
-               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
-                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
-               </CreateItem>
-
-               <!-- Split *remaining* resource files into various groups.. -->
-               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
-                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
-                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
-               </AssignCulture>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
-       <Target Name = "CopyNonResxEmbeddedResources"
-               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
-
-               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
-               <Copy SourceFiles = "@(NonResxWithCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles = "@(NonResxWithNoCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name = "GenerateResources">
-               <GenerateResource
-                       Sources = "@(ResxWithNoCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithNoCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-
-               <GenerateResource
-                       Sources = "@(ResxWithCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-       </Target>
-
-       <Target Name="GenerateSatelliteAssemblies"
-               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
-
-               <AL
-                       Culture = "%(Culture)"
-                       DelaySign="$(DelaySign)"
-                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-                       KeyFile="$(KeyOriginatorFile)"
-                       ToolExe="$(AlToolExe)"
-                       ToolPath="$(AlToolPath)"
-                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
-               </AL>
-
-
-               <CreateItem
-                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
-                       AdditionalMetadata = "Culture=%(Culture)"
-                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
-                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
-               </CreateItem>
-       </Target>
-
-       <PropertyGroup>
-               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
-       </PropertyGroup>
-
-       <Target Name = "CompileLicxFiles"
-               Condition = "'@(LicxFiles)' != ''"
-               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
-               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
-               <LC
-                       Sources = "@(LicxFiles)"
-                       LicenseTarget = "$(TargetFileName)"
-                       OutputDirectory = "$(IntermediateOutputPath)"
-                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
-                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
-                       ToolPath = "$(LCToolPath)"
-                       ToolExe = "$(LCToolExe)">
-
-                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
-                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
-               </LC>
-       </Target>
-
-       <!-- Assign target paths to files that will need to be copied along with the project -->
-       <Target Name = "AssignTargetPaths">
-               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
-               </AssignTargetPath>
-       </Target>
-
-       <Target Name="DeployOutputFiles"
-               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
-
-               <Copy 
-                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
-                       DestinationFolder="$(OutDir)"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)" >
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy
-                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
-                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
-                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="_CopyDeployFilesToOutputDirectory"
-               DependsOnTargets="GetCopyToOutputDirectoryItems;
-                       _CopyDeployFilesToOutputDirectoryAlways;
-                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
-
-       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
-               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
-               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <!-- Copy if newer -->
-       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
-               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-
-       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
-               Inputs="@(AppConfigWithTargetPath)"
-               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(AppConfigWithTargetPath)"
-                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
-
-       <Target Name="GetCopyToOutputDirectoryItems"
-               Outputs="@(AllItemsFullPathWithTargetPath)"
-               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
-
-               <!-- FIXME: handle .vcproj
-                    FIXME: Private ProjectReferences are honored only in 3.5
-               -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetCopyToOutputDirectoryItems"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
-               </MSBuild>
-
-               <!-- Process items from child project. The outputs need to have full path
-                    as they'll be used from other projects -->
-
-               <CreateItem
-                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
-                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-
-               </CreateItem>
-
-               <!-- Process _this_ project's items -->
-
-               <CreateItem
-                       Include="@(NoneWithTargetPath->'%(FullPath)')"
-                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(ContentWithTargetPath->'%(FullPath)')"
-                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
-                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Pre/Post BuildEvents -->
-       <PropertyGroup>
-               <PreBuildEventDependsOn />
-       </PropertyGroup>
-
-       <Target Name="PreBuildEvent"
-               Condition="'$(PreBuildEvent)' != ''"
-               DependsOnTargets="$(PreBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
-       </Target>
-
-       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
-
-               Default: OnBuildSuccess
-               OnBuildSuccess: Run after a successful build
-               OnOutputUpdated: Run only if the output assembly got updates
-               Always: Run always
-       -->
-       <PropertyGroup>
-               <PostBuildEventDependsOn />
-       </PropertyGroup>
-
-       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
-            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
-            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
-            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
-       <Target Name="PostBuildEvent"
-               Condition="'$(PostBuildEvent)' != '' and
-                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
-                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
-               DependsOnTargets="$(PostBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
-       </Target>
-
-       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
-       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
-               </CreateItem>
-       </Target>
-       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
-               </CreateItem>
-       </Target>
-
-       <!-- Rebuild -->
-       <PropertyGroup>
-               <RebuildDependsOn>
-                       BeforeRebuild;
-                       Clean;
-                       $(MSBuildProjectDefaultTargets);
-                       AfterRebuild;
-               </RebuildDependsOn>
-
-               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
-                       BeforeRebuild;
-                       Clean;
-                       Build;
-                       AfterRebuild;
-               </RebuildDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeRebuild" />
-       <Target Name="AfterRebuild" />
-
-       <Target Name="Rebuild"
-               DependsOnTargets="$(RebuildDependsOn)"
-               Outputs="$(TargetPath)"/>
-
-       <!-- Clean -->
-       <Target Name="_RecordCleanFile"
-               DependsOnTargets="_GetCompileOutputsForClean">
-
-               <!-- add to list of previous writes for this platform/config -->
-
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-
-               <!-- CopyLocal files: In case all the projects build to common output
-                    directory, then other projects might depend on some of these
-                    CopyLocal files, so delete only the ones under *this* project
-                    directory -->
-               <FindUnderPath Path="$(MSBuildProjectDirectory)" Files="@(FileWritesShareable)">
-                       <Output TaskParameter="InPath" ItemName="FileWrites"/>
-               </FindUnderPath>
-
-               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
-                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
-               </RemoveDuplicates>
-
-               <WriteLinesToFile
-                       File="$(IntermediateOutputPath)$(CleanFile)"
-                       Lines="@(CombinedFileWrites)"
-                       Overwrite="true"/>
-       </Target>
-
-       <PropertyGroup>
-               <CleanDependsOn>
-                       BeforeClean;
-                       CleanReferencedProjects;
-                       CoreClean;
-                       AfterClean
-               </CleanDependsOn>
-       </PropertyGroup>
-
-       <Target Name="_GetCompileOutputsForClean">
-               <!-- assembly and debug file in the *intermediate output path* -->
-               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-
-               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Get the list of files written, for clean -->
-       <Target Name="_GetCleanFileWrites"
-               DependsOnTargets="_GetCompileOutputsForClean">
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-       </Target>
-
-       <Target Name="CleanReferencedProjects"
-               DependsOnTargets="AssignProjectConfiguration">
-
-               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
-                    else we are building a project directly, from the command line, so
-                    clean the referenced projects -->
-               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="Clean"
-                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
-
-       </Target>
-
-       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
-
-       <!-- Override in project to run before/after clean tasks -->
-       <Target Name="BeforeClean" />
-       <Target Name="AfterClean" />
-
-       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
-               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
-
-               <!-- all previous files written for this platform/config have been deleted,
-                    we can safely remove the file list now -->
-               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
-       </Target>
-
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.tasks b/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.tasks
deleted file mode 100644 (file)
index d1677c9..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
-       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateCSharpManifestResourceName"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/3.5/FrameworkList.xml b/mcs/tools/xbuild/xbuild/3.5/FrameworkList.xml
deleted file mode 100644 (file)
index 1225842..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<FileList  Name=".NET Framework 3.5" TargetFrameworkDirectory="..\..\..\..\3.5" IncludeFramework="v3.0">
-</FileList>
diff --git a/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets
deleted file mode 100644 (file)
index 6d91c77..0000000
+++ /dev/null
@@ -1,778 +0,0 @@
-<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-
-       <Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')"/>
-       
-       <PropertyGroup>
-               <OutputType Condition="'$(OutputType)' == ''">Exe</OutputType>
-               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <AssemblyName Condition="'$(AssemblyName)' == ''">$(MSBuildProjectName)</AssemblyName>
-               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
-               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
-               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
-               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
-               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
-
-               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
-               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
-
-               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
-               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <SkipCopyUnchangedFiles Condition="'$(SkipCopyUnchangedFiles)' == ''">true</SkipCopyUnchangedFiles>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
-               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' != '' and !HasTrailingSlash('$(BaseIntermediateOutputPath)')">$(BaseIntermediateOutputPath)\</BaseIntermediateOutputPath>
-               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
-       </PropertyGroup>
-
-       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
-               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
-               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <IntermediateOutputPath Condition="'$(IntermediateOutputPath)' != '' and !HasTrailingSlash('$(IntermediateOutputPath)')">$(IntermediateOutputPath)\</IntermediateOutputPath>
-       </PropertyGroup>
-
-       <ItemGroup>
-               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
-
-               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
-               <_OutDirItem Include="$(OutDir)"/>
-       </ItemGroup>
-
-       <PropertyGroup>
-               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
-               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
-               <TargetDir Condition=" '$(TargetDir)' == '' ">@(_OutDirItem->'%(FullPath)')</TargetDir>
-               <TargetPath Condition=" '$(TargetPath)' == '' ">@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
-               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets</MSBuildAllProjects>
-
-               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
-       </PropertyGroup>
-
-       <Target Name="_ValidateEssentialProperties">
-               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <!-- If OutDir is specified via the command line, then the earlier check
-                    to add a trailing slash won't have any affect, so error here. -->
-               <Error
-                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
-                       Text="OutDir property must end with a slash."/>
-       </Target>
-
-       <Target Name="PrepareForBuild">
-               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
-
-               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
-                    @(None) and @(Content) -->
-               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
-                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
-                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
-               </CreateItem>
-
-               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
-                       Condition="'$(AppConfig)' == ''">
-                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
-               </FindAppConfigFile>
-
-               <MakeDir 
-                       Directories="$(OutDir);$(IntermediateOutputPath);@(DocFileItem->'%(RelativeDir)')"
-               />
-       </Target>
-
-       <PropertyGroup>
-               <GetFrameworkPathsDependsOn />
-       </PropertyGroup>
-       <Target Name="GetFrameworkPaths" DependsOnTargets="$(GetFrameworkPathsDependsOn)">
-               <GetFrameworkPath>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
-                               TaskParameter="FrameworkVersion35Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion30Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion20Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-               </GetFrameworkPath>
-               <CreateProperty Value="@(_CombinedTargetFrameworkDirectoriesItem)">
-                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
-               </CreateProperty>
-
-               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
-                       Condition="'$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
-       </Target>
-
-       <PropertyGroup>
-               <GetReferenceAssemblyPathsDependsOn />
-       </PropertyGroup>
-       <!-- Multi-targeting against "framework packs" is not supported with ToolsVersion < 4.0,
-            this target is just a place holder, can be overridden -->
-       <Target Name="GetReferenceAssemblyPaths" DependsOnTargets="$(GetReferenceAssemblyPathsDependsOn)" />
-
-       <PropertyGroup>
-               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
-                       .exe;
-                       .dll
-               </AllowedReferenceAssemblyFileExtensions>
-
-               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
-                       .exe.mdb;
-                       .dll.mdb;
-                       .xml
-               </AllowedReferenceRelatedFileExtensions>
-
-               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
-                       {CandidateAssemblyFiles};
-                       $(ReferencePath);
-                       @(AdditionalReferencePath);
-                       {HintPathFromItem};
-                       {TargetFrameworkDirectory};
-                       {PkgConfig};
-                       {GAC};
-                       {RawFileName};
-                       $(OutDir)
-               </AssemblySearchPaths>
-
-               <ResolveReferencesDependsOn>
-                       BeforeResolveReferences;
-                       ResolveProjectReferences;
-                       ResolveAssemblyReferences;
-                       AfterResolveReferences
-               </ResolveReferencesDependsOn>
-
-               <ResolveAssemblyReferencesDependsOn>
-                       GetFrameworkPaths;
-                       GetReferenceAssemblyPaths;
-                       PrepareForBuild
-               </ResolveAssemblyReferencesDependsOn>
-       </PropertyGroup>
-
-       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
-
-       <Target Name="BeforeResolveReferences" />
-       <Target Name="AfterResolveReferences" />
-
-       <Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
-               <ResolveAssemblyReference
-                       Assemblies="@(Reference)"
-                       AssemblyFiles="@(ChildProjectReferences)"
-                       SearchPaths="$(AssemblySearchPaths)"
-                       CandidateAssemblyFiles="@(Content);@(None)"
-                       TargetFrameworkDirectories="$(TargetFrameworkDirectory)"
-                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
-                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
-                       FindDependencies="true"
-                       FindSatellites="true"
-                       FindRelatedFiles="true"
-                       TargetFrameworkVersion="$(TargetFrameworkVersion)"
-               >
-                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
-                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
-                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
-                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
-                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
-                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
-               </ResolveAssemblyReference>
-       </Target>
-
-       <Target
-               Name="AssignProjectConfiguration"
-               Condition="'@(ProjectReference)' != ''">
-
-               <!-- assign configs if building a solution file -->
-               <AssignProjectConfiguration
-                       ProjectReferences = "@(ProjectReference)"
-                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
-                       Condition="'$(BuildingSolutionFile)' == 'true'">
-
-                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
-               </AssignProjectConfiguration>
-
-               <!-- Else, just -->
-               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Split projects into 2 lists
-               ProjectReferenceWithConfigurationExistent: Projects existent on disk
-               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
-
-       <Target Name="SplitProjectReferencesByExistent"
-               DependsOnTargets="AssignProjectConfiguration">
-
-               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
-                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
-                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-               </CreateItem>
-       </Target>
-
-       <Target
-               Name="ResolveProjectReferences"
-               DependsOnTargets="SplitProjectReferencesByExistent"
-       >
-               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
-                    been built, so just get the target paths -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetTargetPath"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <!-- Building a project directly, build the referenced the projects also -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
-                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
-       </Target>
-
-       <Target Name = "CopyFilesMarkedCopyLocal">
-               <Copy
-                       SourceFiles="@(ReferenceCopyLocalPaths)"
-                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWritesShareable"/>
-               </Copy>
-       </Target>
-
-       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
-               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
-                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
-               </CreateProperty>
-       </Target>
-
-       <PropertyGroup>
-               <BuildDependsOn>
-                       BeforeBuild;
-                       CoreBuild;
-                       AfterBuild
-               </BuildDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeBuild"/>
-       <Target Name="AfterBuild"/>
-
-       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
-
-       <PropertyGroup>
-               <CoreBuildDependsOn>
-                       PrepareForBuild;
-                       GetFrameworkPaths;
-                       GetReferenceAssemblyPaths;
-                       PreBuildEvent;
-                       ResolveReferences;
-                       CopyFilesMarkedCopyLocal;
-                       PrepareResources;
-                       Compile;
-                       PrepareForRun;
-                       DeployOutputFiles;
-                       _RecordCleanFile;
-                       PostBuildEvent
-               </CoreBuildDependsOn>
-       </PropertyGroup>
-
-       <Target
-               Name="CoreBuild"
-               DependsOnTargets="$(CoreBuildDependsOn)"
-               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
-
-               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
-                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
-
-               <OnError ExecuteTargets="_RecordCleanFile" />
-       </Target>
-
-       <PropertyGroup>
-               <CompileDependsOn>
-                       ResolveReferences;
-                       BeforeCompile;
-                       _TimestampBeforeCompile;
-                       CoreCompile;
-                       _TimestampAfterCompile;
-                       AfterCompile
-               </CompileDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeCompile" />
-       <Target Name="AfterCompile" />
-
-       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
-
-       <PropertyGroup>
-               <PrepareForRunDependsOn>
-                       DeployOutputFiles
-               </PrepareForRunDependsOn>
-       </PropertyGroup>
-       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
-
-       <PropertyGroup>
-               <PrepareResourcesDependsOn>
-                       AssignTargetPaths;
-                       SplitResourcesByCulture;
-                       CreateManifestResourceNames;
-                       CopyNonResxEmbeddedResources;
-                       GenerateResources;
-                       GenerateSatelliteAssemblies;
-                       CompileLicxFiles
-               </PrepareResourcesDependsOn>
-       </PropertyGroup>
-       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
-
-       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
-               <!-- Extract .licx files into @(LicxFiles) -->
-               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
-                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
-               </CreateItem>
-
-               <!-- Split *remaining* resource files into various groups.. -->
-               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
-                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
-                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
-               </AssignCulture>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
-       <Target Name = "CopyNonResxEmbeddedResources"
-               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
-
-               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
-               <Copy SourceFiles = "@(NonResxWithCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles = "@(NonResxWithNoCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name = "GenerateResources">
-               <GenerateResource
-                       Sources = "@(ResxWithNoCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithNoCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-
-               <GenerateResource
-                       Sources = "@(ResxWithCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-       </Target>
-
-       <Target Name="GenerateSatelliteAssemblies"
-               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
-
-               <AL
-                       Culture = "%(Culture)"
-                       DelaySign="$(DelaySign)"
-                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-                       KeyFile="$(KeyOriginatorFile)"
-                       ToolExe="$(AlToolExe)"
-                       ToolPath="$(AlToolPath)"
-                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
-               </AL>
-
-
-               <CreateItem
-                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
-                       AdditionalMetadata = "Culture=%(Culture)"
-                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
-                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
-               </CreateItem>
-       </Target>
-
-       <PropertyGroup>
-               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
-       </PropertyGroup>
-
-       <Target Name = "CompileLicxFiles"
-               Condition = "'@(LicxFiles)' != ''"
-               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
-               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
-               <LC
-                       Sources = "@(LicxFiles)"
-                       LicenseTarget = "$(TargetFileName)"
-                       OutputDirectory = "$(IntermediateOutputPath)"
-                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
-                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
-                       ToolPath = "$(LCToolPath)"
-                       ToolExe = "$(LCToolExe)">
-
-                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
-                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
-               </LC>
-       </Target>
-
-       <!-- Assign target paths to files that will need to be copied along with the project -->
-       <Target Name = "AssignTargetPaths">
-               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
-               </AssignTargetPath>
-       </Target>
-
-       <Target Name="DeployOutputFiles"
-               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
-
-               <Copy 
-                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
-                       DestinationFolder="$(OutDir)"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)" >
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy
-                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
-                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
-                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="_CopyDeployFilesToOutputDirectory"
-               DependsOnTargets="GetCopyToOutputDirectoryItems;
-                       _CopyDeployFilesToOutputDirectoryAlways;
-                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
-
-       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
-               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
-               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <!-- Copy if newer -->
-       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
-               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-
-       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
-               Inputs="@(AppConfigWithTargetPath)"
-               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(AppConfigWithTargetPath)"
-                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
-
-       <Target Name="GetCopyToOutputDirectoryItems"
-               Outputs="@(AllItemsFullPathWithTargetPath)"
-               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
-
-               <!-- FIXME: handle .vcproj
-                    FIXME: Private ProjectReferences are honored only in 3.5
-               -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetCopyToOutputDirectoryItems"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
-               </MSBuild>
-
-               <!-- Process items from child project. The outputs need to have full path
-                    as they'll be used from other projects -->
-
-               <CreateItem
-                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
-                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-
-               </CreateItem>
-
-               <!-- Process _this_ project's items -->
-
-               <CreateItem
-                       Include="@(NoneWithTargetPath->'%(FullPath)')"
-                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(ContentWithTargetPath->'%(FullPath)')"
-                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
-                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Pre/Post BuildEvents -->
-       <PropertyGroup>
-               <PreBuildEventDependsOn />
-       </PropertyGroup>
-
-       <Target Name="PreBuildEvent"
-               Condition="'$(PreBuildEvent)' != ''"
-               DependsOnTargets="$(PreBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
-       </Target>
-
-       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
-
-               Default: OnBuildSuccess
-               OnBuildSuccess: Run after a successful build
-               OnOutputUpdated: Run only if the output assembly got updates
-               Always: Run always
-       -->
-       <PropertyGroup>
-               <PostBuildEventDependsOn />
-       </PropertyGroup>
-
-       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
-            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
-            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
-            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
-       <Target Name="PostBuildEvent"
-               Condition="'$(PostBuildEvent)' != '' and
-                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
-                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
-               DependsOnTargets="$(PostBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
-       </Target>
-
-       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
-       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
-               </CreateItem>
-       </Target>
-       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
-               </CreateItem>
-       </Target>
-
-       <!-- Rebuild -->
-       <PropertyGroup>
-               <RebuildDependsOn>
-                       BeforeRebuild;
-                       Clean;
-                       $(MSBuildProjectDefaultTargets);
-                       AfterRebuild;
-               </RebuildDependsOn>
-
-               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
-                       BeforeRebuild;
-                       Clean;
-                       Build;
-                       AfterRebuild;
-               </RebuildDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeRebuild" />
-       <Target Name="AfterRebuild" />
-
-       <Target Name="Rebuild"
-               DependsOnTargets="$(RebuildDependsOn)"
-               Outputs="$(TargetPath)"/>
-
-       <!-- Clean -->
-       <Target Name="_RecordCleanFile"
-               DependsOnTargets="_GetCompileOutputsForClean">
-
-               <!-- add to list of previous writes for this platform/config -->
-
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-
-               <!-- CopyLocal files: In case all the projects build to common output
-                    directory, then other projects might depend on some of these
-                    CopyLocal files, so delete only the ones under *this* project
-                    directory -->
-               <FindUnderPath Path="$(MSBuildProjectDirectory)" Files="@(FileWritesShareable)">
-                       <Output TaskParameter="InPath" ItemName="FileWrites"/>
-               </FindUnderPath>
-
-               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
-                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
-               </RemoveDuplicates>
-
-               <WriteLinesToFile
-                       File="$(IntermediateOutputPath)$(CleanFile)"
-                       Lines="@(CombinedFileWrites)"
-                       Overwrite="true"/>
-       </Target>
-
-       <PropertyGroup>
-               <CleanDependsOn>
-                       BeforeClean;
-                       CleanReferencedProjects;
-                       CoreClean;
-                       AfterClean
-               </CleanDependsOn>
-       </PropertyGroup>
-
-       <Target Name="_GetCompileOutputsForClean">
-               <!-- assembly and debug file in the *intermediate output path* -->
-               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-
-               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Get the list of files written, for clean -->
-       <Target Name="_GetCleanFileWrites"
-               DependsOnTargets="_GetCompileOutputsForClean">
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-       </Target>
-
-       <Target Name="CleanReferencedProjects"
-               DependsOnTargets="AssignProjectConfiguration">
-
-               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
-                    else we are building a project directly, from the command line, so
-                    clean the referenced projects -->
-               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="Clean"
-                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
-
-       </Target>
-
-       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
-
-       <!-- Override in project to run before/after clean tasks -->
-       <Target Name="BeforeClean" />
-       <Target Name="AfterClean" />
-
-       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
-               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
-
-               <!-- all previous files written for this platform/config have been deleted,
-                    we can safely remove the file list now -->
-               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
-       </Target>
-
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.tasks b/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.tasks
deleted file mode 100644 (file)
index 397d68c..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
-       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateCSharpManifestResourceName"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/4.0/FrameworkList.xml b/mcs/tools/xbuild/xbuild/4.0/FrameworkList.xml
deleted file mode 100644 (file)
index 7012794..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<FileList  Name=".NET Framework 4" TargetFrameworkDirectory="..\..\..\..\4.0">
-</FileList>
diff --git a/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets
deleted file mode 100644 (file)
index 6e4b73e..0000000
+++ /dev/null
@@ -1,917 +0,0 @@
-<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <PropertyGroup>
-               <ImportByWildcardBeforeMicrosoftCommonTargets Condition="'$(ImportByWildcardBeforeMicrosoftCommonTargets)' == ''">true</ImportByWildcardBeforeMicrosoftCommonTargets>
-               <ImportByWildcardAfterMicrosoftCommonTargets Condition="'$(ImportByWildcardAfterMicrosoftCommonTargets)' == ''">true</ImportByWildcardAfterMicrosoftCommonTargets>
-       </PropertyGroup>
-
-       <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportBefore\*"
-               Condition="'$(ImportByWildcardBeforeMicrosoftCommonTargets)' == 'true' and Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportBefore')"/>
-
-       <Import Project="$(MSBuildProjectFullPath).user" Condition="Exists('$(MSBuildProjectFullPath).user')"/> 
-       
-       <PropertyGroup>
-               <OutputType Condition="'$(OutputType)' == ''">Exe</OutputType>
-               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <AssemblyName Condition="'$(AssemblyName)' == ''">$(MSBuildProjectName)</AssemblyName>
-               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
-               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
-               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
-
-               <TargetFrameworkIdentifier Condition="'$(TargetFrameworkIdentifier)' == ''">.NETFramework</TargetFrameworkIdentifier>
-               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v4.0</TargetFrameworkVersion>
-
-               <TargetFrameworkMoniker Condition="'$(TargetFrameworkMoniker)' == '' and '$(TargetFrameworkProfile)' != ''">$(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion),Profile=$(TargetFrameworkProfile)</TargetFrameworkMoniker>
-               <TargetFrameworkMoniker Condition="'$(TargetFrameworkMoniker)' == ''">$(TargetFrameworkIdentifier),Version=$(TargetFrameworkVersion)</TargetFrameworkMoniker>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
-               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
-
-               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
-               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
-
-               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
-               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
-
-               <AddAdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == ''">true</AddAdditionalExplicitAssemblyReferences>
-               <AdditionalExplicitAssemblyReferences Condition="'$(AddAdditionalExplicitAssemblyReferences)' == 'true' and '$(TargetFrameworkVersion)' != 'v2.0' and '$(TargetFrameworkVersion)' != 'v3.0'">System.Core;$(AdditionalExplicitAssemblyReferences)</AdditionalExplicitAssemblyReferences>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <SkipCopyUnchangedFiles Condition="'$(SkipCopyUnchangedFiles)' == ''">true</SkipCopyUnchangedFiles>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
-               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' != '' and !HasTrailingSlash('$(BaseIntermediateOutputPath)')">$(BaseIntermediateOutputPath)\</BaseIntermediateOutputPath>
-               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
-       </PropertyGroup>
-
-       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
-               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
-               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <IntermediateOutputPath Condition="'$(IntermediateOutputPath)' != '' and !HasTrailingSlash('$(IntermediateOutputPath)')">$(IntermediateOutputPath)\</IntermediateOutputPath>
-       </PropertyGroup>
-
-       <ItemGroup>
-               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
-
-               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
-               <_OutDirItem Include="$(OutDir)"/>
-       </ItemGroup>
-
-       <PropertyGroup>
-               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
-               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
-               <TargetDir Condition=" '$(TargetDir)' == '' ">@(_OutDirItem->'%(FullPath)')</TargetDir>
-               <TargetPath Condition=" '$(TargetPath)' == '' ">@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
-               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildProjectFullPath);$(MSBuildToolsPath)\Microsoft.Common.targets</MSBuildAllProjects>
-               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
-               <TargetingClr2Framework Condition="('$(TargetFrameworkIdentifier)' == '.NETFramework') and ('$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5')">true</TargetingClr2Framework>
-       </PropertyGroup>
-
-       <Target Name="_ValidateEssentialProperties">
-               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <!-- If OutDir is specified via the command line, then the earlier check
-                    to add a trailing slash won't have any affect, so error here. -->
-               <Error
-                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
-                       Text="OutDir property must end with a slash."/>
-       </Target>
-
-       <Target Name="PrepareForBuild">
-               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
-
-               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
-                    @(None) and @(Content) -->
-               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
-                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
-                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
-               </CreateItem>
-
-               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
-                       Condition="'$(AppConfig)' == ''">
-                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
-               </FindAppConfigFile>
-
-               <MakeDir 
-                       Directories="$(OutDir);$(IntermediateOutputPath);@(DocFileItem->'%(RelativeDir)')"
-               />
-       </Target>
-
-       <PropertyGroup>
-               <GetFrameworkPathsDependsOn />
-       </PropertyGroup>
-       <Target Name="GetFrameworkPaths"
-               Condition="'$(TargetFrameworkIdentifier)' == '' or '$(TargetFrameworkIdentifier)' == '.NETFramework'"
-               DependsOnTargets="$(GetFrameworkPathsDependsOn)">
-               <GetFrameworkPath>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v4.5'"
-                               TaskParameter="FrameworkVersion45Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v4.0'"
-                               TaskParameter="FrameworkVersion40Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
-                               TaskParameter="FrameworkVersion35Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion30Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion20Path"
-                               ItemName="_CombinedTargetFrameworkDirectoriesItem"/>
-               </GetFrameworkPath>
-               <CreateProperty Value="@(_CombinedTargetFrameworkDirectoriesItem)">
-                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
-               </CreateProperty>
-
-               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
-                       Condition="'$(TargetFrameworkVersion)' != 'v4.5' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
-       </Target>
-
-       <PropertyGroup>
-               <GetReferenceAssemblyPathsDependsOn />
-       </PropertyGroup>
-       <Target Name="GetReferenceAssemblyPaths" DependsOnTargets="$(GetReferenceAssemblyPathsDependsOn)">
-               <!-- in case of .NETFramework, $(TargetFrameworkDirectory) would have been set by
-               GetFrameworkPaths, if it hasn't been changed, then clear it, to avoid duplicates -->
-               <CreateProperty Value="" Condition="'@(_CombinedTargetFrameworkDirectoriesItem)' == '$(TargetFrameworkDirectory)'">
-                       <Output TaskParameter="Value" PropertyName="TargetFrameworkDirectory"/>
-               </CreateProperty>
-
-               <GetReferenceAssemblyPaths
-                       Condition="'$(TargetFrameworkMoniker)' != '' and '$(_TargetFrameworkDirectories)' == ''"
-                       TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
-                       RootPath="$(TargetFrameworkRootPath)">
-
-                       <Output TaskParameter="ReferenceAssemblyPaths" PropertyName="_TargetFrameworkDirectories"/>
-                       <Output TaskParameter="FullFrameworkReferenceAssemblyPaths" PropertyName="_FullFrameworkReferenceAssemblyPaths"/>
-                       <Output TaskParameter="TargetFrameworkMonikerDisplayName" PropertyName="TargetFrameworkMonikerDisplayName"/>
-               </GetReferenceAssemblyPaths>
-
-               
-               <!-- Remove duplicates. -->
-               <ItemGroup>
-                       <_TargetFrameworkDirectories Include="$(_TargetFrameworkDirectories);$(TargetFrameworkDirectory)" KeepDuplicates="false" />
-               </ItemGroup>
-               <PropertyGroup>
-                       <TargetFrameworkDirectory>@(_TargetFrameworkDirectories)</TargetFrameworkDirectory>
-               </PropertyGroup>
-               
-               <ItemGroup Condition="'$(ImplicitlyExpandDesignTimeFacades)' == 'true'">
-                       <DesignTimeFacadeDirectoryRoots Include="$(TargetFrameworkDirectory)" />
-                       <DesignTimeFacadeDirectories Include="%(DesignTimeFacadeDirectoryRoots.Identity)\Facades\" Condition="Exists('%(DesignTimeFacadeDirectoryRoots.Identity)\Facades\')" />
-                       <_DesignTimeFacadeAssemblies Include="%(DesignTimeFacadeDirectories.Identity)\*.dll"/>
-               </ItemGroup>
-               
-               <PropertyGroup Condition="'@(DesignTimeFacadeDirectories)' != ''">
-                       <TargetFrameworkDirectory>$(TargetFrameworkDirectory);@(DesignTimeFacadeDirectories)</TargetFrameworkDirectory>
-               </PropertyGroup>
-               
-       </Target>
-
-       <PropertyGroup>
-               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
-                       .exe;
-                       .dll
-               </AllowedReferenceAssemblyFileExtensions>
-
-               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
-                       .exe.mdb;
-                       .dll.mdb;
-                       .xml
-               </AllowedReferenceRelatedFileExtensions>
-
-               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
-                       {CandidateAssemblyFiles};
-                       $(ReferencePath);
-                       @(AdditionalReferencePath);
-                       {HintPathFromItem};
-                       {TargetFrameworkDirectory};
-                       {PkgConfig};
-                       {GAC};
-                       {RawFileName};
-                       $(OutDir)
-               </AssemblySearchPaths>
-
-               <ResolveReferencesDependsOn>
-                       BeforeResolveReferences;
-                       ResolveProjectReferences;
-                       ResolveAssemblyReferences;
-                       AfterResolveReferences
-               </ResolveReferencesDependsOn>
-
-               <ResolveAssemblyReferencesDependsOn>
-                       GetFrameworkPaths;
-                       GetReferenceAssemblyPaths;
-                       PrepareForBuild
-               </ResolveAssemblyReferencesDependsOn>
-       </PropertyGroup>
-       
-       <PropertyGroup Condition="'$(TargetFrameworkMoniker)' != ''">
-               <TargetFrameworkMonikerAssemblyAttributesPath Condition="'$(TargetFrameworkMonikerAssemblyAttributesPath)' == ''">$(IntermediateOutputPath)$(TargetFrameworkMoniker).AssemblyAttribute$(DefaultLanguageSourceExtension)</TargetFrameworkMonikerAssemblyAttributesPath>
-               <GenerateTargetFrameworkAttribute Condition="'$(GenerateTargetFrameworkAttribute)' == '' and '$(TargetFrameworkMoniker)' 
-       != '' and '$(TargetingClr2Framework)' != 'true'">true</GenerateTargetFrameworkAttribute>
-       </PropertyGroup>
-       
-       <ItemGroup Condition="'$(GenerateTargetFrameworkAttribute)' == 'true'">
-               <FileWrites Include="$(TargetFrameworkMonikerAssemblyAttributesPath)" />
-       </ItemGroup>
-       
-       <Target Name="GenerateTargetFrameworkMonikerAttribute"
-               DependsOnTargets="PrepareForBuild;GetReferenceAssemblyPaths"
-               Inputs="$(MSBuildToolsPath)\Microsoft.Common.targets"
-               Outputs="$(TargetFrameworkMonikerAssemblyAttributesPath)"
-               Condition="'$(GenerateTargetFrameworkAttribute)' == 'true'">
-               
-               <WriteLinesToFile
-                       File="$(TargetFrameworkMonikerAssemblyAttributesPath)"
-                       Lines="$(TargetFrameworkMonikerAssemblyAttributeText)"
-                       Overwrite="true"
-                       ContinueOnError="true"
-                       Condition="'@(Compile)' != '' and '$(TargetFrameworkMonikerAssemblyAttributeText)' != ''"
-               />
-               
-               <ItemGroup Condition="'@(Compile)' != '' and '$(TargetFrameworkMonikerAssemblyAttributeText)' != ''">
-                       <Compile Include="$(TargetFrameworkMonikerAssemblyAttributesPath)"/>
-               </ItemGroup>
-       </Target>
-
-       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
-
-       <Target Name="BeforeResolveReferences" />
-       <Target Name="AfterResolveReferences" />
-
-       <Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
-               <CreateItem Include="@(Reference)" Exclude="$(AdditionalExplicitAssemblyReferences)">
-                       <Output TaskParameter="Include" ItemName="_Reference"/>
-               </CreateItem>
-
-               <CreateItem Include="$(AdditionalExplicitAssemblyReferences)">
-                       <Output TaskParameter="Include" ItemName="_Reference"/>
-               </CreateItem>
-
-               <ResolveAssemblyReference
-                       Assemblies="@(_Reference)"
-                       AssemblyFiles="@(ChildProjectReferences)"
-                       SearchPaths="$(AssemblySearchPaths)"
-                       CandidateAssemblyFiles="@(Content);@(None)"
-                       TargetFrameworkDirectories="$(TargetFrameworkDirectory)"
-                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
-                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
-                       FindDependencies="true"
-                       FindSatellites="true"
-                       FindRelatedFiles="true"
-                       TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
-                       TargetFrameworkMonikerDisplayName="$(TargetFrameworkMonikerDisplayName)"
-                       TargetFrameworkVersion="$(TargetFrameworkVersion)"
-               >
-                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
-                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
-                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="ReferenceDependencyPaths"/>
-                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
-                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
-                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
-                       
-                       <!-- FIXME: backwards compatibility -->
-                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
-               </ResolveAssemblyReference>
-       </Target>
-
-       <Target
-               Name="AssignProjectConfiguration"
-               Condition="'@(ProjectReference)' != ''">
-
-               <!-- assign configs if building a solution file -->
-               <AssignProjectConfiguration
-                       ProjectReferences = "@(ProjectReference)"
-                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
-                       Condition="'$(BuildingSolutionFile)' == 'true'">
-
-                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
-               </AssignProjectConfiguration>
-
-               <!-- Else, just -->
-               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Split projects into 2 lists
-               ProjectReferenceWithConfigurationExistent: Projects existent on disk
-               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
-
-       <Target Name="SplitProjectReferencesByExistent"
-               DependsOnTargets="AssignProjectConfiguration">
-
-               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
-                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
-                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-               </CreateItem>
-       </Target>
-
-       <Target
-               Name="ResolveProjectReferences"
-               DependsOnTargets="SplitProjectReferencesByExistent"
-       >
-               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
-                    been built, so just get the target paths -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetTargetPath"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <!-- Building a project directly, build the referenced the projects also -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
-                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
-       </Target>
-
-       <Target Name = "CopyFilesMarkedCopyLocal">
-               <Copy
-                       SourceFiles="@(ReferenceCopyLocalPaths)"
-                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWritesShareable"/>
-               </Copy>
-       </Target>
-
-       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
-               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
-                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
-               </CreateProperty>
-       </Target>
-
-       <PropertyGroup>
-               <BuildDependsOn>
-                       BuildOnlySettings;
-                       BeforeBuild;
-                       CoreBuild;
-                       AfterBuild
-               </BuildDependsOn>
-       </PropertyGroup>
-       
-       <Target Name="BuildOnlySettings"/>
-       <Target Name="BeforeBuild"/>
-       <Target Name="AfterBuild"/>
-
-       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
-
-       <PropertyGroup>
-               <CoreBuildDependsOn>
-                       PrepareForBuild;
-                       GetFrameworkPaths;
-                       GetReferenceAssemblyPaths;
-                       PreBuildEvent;
-                       ResolveReferences;
-                       CopyFilesMarkedCopyLocal;
-                       PrepareResources;
-                       Compile;
-                       PrepareForRun;
-                       DeployOutputFiles;
-                       _RecordCleanFile;
-                       PostBuildEvent
-               </CoreBuildDependsOn>
-       </PropertyGroup>
-
-       <Target
-               Name="CoreBuild"
-               DependsOnTargets="$(CoreBuildDependsOn)"
-               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
-
-               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
-                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
-
-               <OnError ExecuteTargets="_RecordCleanFile" />
-       </Target>
-
-       <PropertyGroup>
-               <CompileDependsOn>
-                       ResolveReferences;
-                       GenerateTargetFrameworkMonikerAttribute;
-                       BeforeCompile;
-                       _TimestampBeforeCompile;
-                       CoreCompile;
-                       _TimestampAfterCompile;
-                       AfterCompile
-               </CompileDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeCompile" />
-       <Target Name="AfterCompile" />
-
-       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
-
-       <PropertyGroup>
-               <PrepareForRunDependsOn>
-                       DeployOutputFiles
-               </PrepareForRunDependsOn>
-       </PropertyGroup>
-       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
-
-       <PropertyGroup>
-               <PrepareResourcesDependsOn>
-                       AssignTargetPaths;
-                       SplitResourcesByCulture;
-                       CreateManifestResourceNames;
-                       CopyNonResxEmbeddedResources;
-                       GenerateResources;
-                       GenerateSatelliteAssemblies;
-                       CompileLicxFiles
-               </PrepareResourcesDependsOn>
-       </PropertyGroup>
-       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
-
-       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
-               <!-- Extract .licx files into @(LicxFiles) -->
-               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
-                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
-               </CreateItem>
-
-               <!-- Split *remaining* resource files into various groups.. -->
-               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
-                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
-                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
-               </AssignCulture>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
-       <Target Name = "CopyNonResxEmbeddedResources"
-               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
-
-               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
-               <Copy SourceFiles = "@(NonResxWithCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles = "@(NonResxWithNoCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name = "GenerateResources">
-               <GenerateResource
-                       Sources = "@(ResxWithNoCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithNoCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-
-               <GenerateResource
-                       Sources = "@(ResxWithCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-       </Target>
-
-       <Target Name="GenerateSatelliteAssemblies"
-               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
-
-               <AL
-                       Culture = "%(Culture)"
-                       DelaySign="$(DelaySign)"
-                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-                       KeyFile="$(KeyOriginatorFile)"
-                       ToolExe="$(AlToolExe)"
-                       ToolPath="$(AlToolPath)"
-                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
-               </AL>
-
-
-               <CreateItem
-                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
-                       AdditionalMetadata = "Culture=%(Culture)"
-                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
-                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
-               </CreateItem>
-       </Target>
-
-       <PropertyGroup>
-               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
-       </PropertyGroup>
-
-       <Target Name = "CompileLicxFiles"
-               Condition = "'@(LicxFiles)' != ''"
-               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
-               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
-               <LC
-                       Sources = "@(LicxFiles)"
-                       LicenseTarget = "$(TargetFileName)"
-                       OutputDirectory = "$(IntermediateOutputPath)"
-                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
-                       ReferencedAssemblies = "@(ReferencePath);@(ReferenceDependencyPaths)"
-                       ToolPath = "$(LCToolPath)"
-                       ToolExe = "$(LCToolExe)">
-
-                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
-                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
-               </LC>
-       </Target>
-
-       <!-- Assign target paths to files that will need to be copied along with the project -->
-       <Target Name = "AssignTargetPaths">
-               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
-               </AssignTargetPath>
-       </Target>
-
-       <Target Name="DeployOutputFiles"
-               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
-
-               <Copy 
-                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
-                       DestinationFolder="$(OutDir)"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)" >
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy
-                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
-                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
-                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="_CopyDeployFilesToOutputDirectory"
-               DependsOnTargets="GetCopyToOutputDirectoryItems;
-                       _CopyDeployFilesToOutputDirectoryAlways;
-                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
-
-       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
-               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
-               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')"
-                       SkipUnchangedFiles="$(SkipCopyUnchangedFiles)"> 
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <!-- Copy if newer -->
-       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
-               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-
-       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
-               Inputs="@(AppConfigWithTargetPath)"
-               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(AppConfigWithTargetPath)"
-                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
-
-       <Target Name="GetCopyToOutputDirectoryItems"
-               Outputs="@(AllItemsFullPathWithTargetPath)"
-               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
-
-               <!-- FIXME: handle .vcproj
-                    FIXME: Private ProjectReferences are honored only in 3.5
-               -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetCopyToOutputDirectoryItems"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
-               </MSBuild>
-
-               <!-- Process items from child project. The outputs need to have full path
-                    as they'll be used from other projects -->
-
-               <CreateItem
-                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
-                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-
-               </CreateItem>
-
-               <!-- Process _this_ project's items -->
-
-               <CreateItem
-                       Include="@(NoneWithTargetPath->'%(FullPath)')"
-                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(ContentWithTargetPath->'%(FullPath)')"
-                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
-                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Pre/Post BuildEvents -->
-       <PropertyGroup>
-               <PreBuildEventDependsOn />
-       </PropertyGroup>
-
-       <Target Name="PreBuildEvent"
-               Condition="'$(PreBuildEvent)' != ''"
-               DependsOnTargets="$(PreBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
-       </Target>
-
-       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
-
-               Default: OnBuildSuccess
-               OnBuildSuccess: Run after a successful build
-               OnOutputUpdated: Run only if the output assembly got updates
-               Always: Run always
-       -->
-       <PropertyGroup>
-               <PostBuildEventDependsOn />
-       </PropertyGroup>
-
-       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
-            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
-            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
-            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
-       <Target Name="PostBuildEvent"
-               Condition="'$(PostBuildEvent)' != '' and
-                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
-                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
-               DependsOnTargets="$(PostBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
-       </Target>
-
-       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
-       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
-               </CreateItem>
-       </Target>
-       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
-               </CreateItem>
-       </Target>
-
-       <!-- Rebuild -->
-       <PropertyGroup>
-               <RebuildDependsOn>
-                       BeforeRebuild;
-                       Clean;
-                       $(MSBuildProjectDefaultTargets);
-                       AfterRebuild;
-               </RebuildDependsOn>
-
-               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
-                       BeforeRebuild;
-                       Clean;
-                       Build;
-                       AfterRebuild;
-               </RebuildDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeRebuild" />
-       <Target Name="AfterRebuild" />
-
-       <Target Name="Rebuild"
-               DependsOnTargets="$(RebuildDependsOn)"
-               Outputs="$(TargetPath)"/>
-
-       <!-- Clean -->
-       <Target Name="_RecordCleanFile"
-               DependsOnTargets="_GetCompileOutputsForClean">
-
-               <!-- add to list of previous writes for this platform/config -->
-
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-
-               <!-- CopyLocal files: In case all the projects build to common output
-                    directory, then other projects might depend on some of these
-                    CopyLocal files, so delete only the ones under *this* project
-                    directory -->
-               <FindUnderPath Path="$(MSBuildProjectDirectory)" Files="@(FileWritesShareable)">
-                       <Output TaskParameter="InPath" ItemName="FileWrites"/>
-               </FindUnderPath>
-
-               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
-                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
-               </RemoveDuplicates>
-
-               <WriteLinesToFile
-                       File="$(IntermediateOutputPath)$(CleanFile)"
-                       Lines="@(CombinedFileWrites)"
-                       Overwrite="true"/>
-       </Target>
-
-       <PropertyGroup>
-               <CleanDependsOn>
-                       BeforeClean;
-                       CleanReferencedProjects;
-                       CoreClean;
-                       AfterClean
-               </CleanDependsOn>
-       </PropertyGroup>
-
-       <Target Name="_GetCompileOutputsForClean">
-               <!-- assembly and debug file in the *intermediate output path* -->
-               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-
-               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Get the list of files written, for clean -->
-       <Target Name="_GetCleanFileWrites"
-               DependsOnTargets="_GetCompileOutputsForClean">
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-       </Target>
-
-       <Target Name="CleanReferencedProjects"
-               DependsOnTargets="AssignProjectConfiguration">
-
-               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
-                    else we are building a project directly, from the command line, so
-                    clean the referenced projects -->
-               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="Clean"
-                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
-
-       </Target>
-
-       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
-
-       <!-- Override in project to run before/after clean tasks -->
-       <Target Name="BeforeClean" />
-       <Target Name="AfterClean" />
-
-       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
-               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
-
-               <!-- all previous files written for this platform/config have been deleted,
-                    we can safely remove the file list now -->
-               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
-       </Target>
-       
-       <PropertyGroup>
-               <ImplicitlyExpandDesignTimeFacades>true</ImplicitlyExpandDesignTimeFacades>
-
-               <ResolveReferencesDependsOn>
-                       $(ResolveReferencesDependsOn);
-                       ImplicitlyExpandDesignTimeFacades
-               </ResolveReferencesDependsOn>
-
-               <ImplicitlyExpandDesignTimeFacadesDependsOn>
-                       $(ImplicitlyExpandDesignTimeFacadesDependsOn);
-                       GetReferenceAssemblyPaths
-               </ImplicitlyExpandDesignTimeFacadesDependsOn>
-       </PropertyGroup>
-       
-       <Target Name="ImplicitlyExpandDesignTimeFacades" Condition="'$(ImplicitlyExpandDesignTimeFacades)' == 'true'" DependsOnTargets="$(ImplicitlyExpandDesignTimeFacadesDependsOn)">
-       
-               <PropertyGroup>
-                       <_HasReferenceToSystemRuntime Condition="'%(_ResolvedDependencyFiles.Filename)' == 'System.Runtime'">true</_HasReferenceToSystemRuntime>
-               </PropertyGroup>
-
-               <ItemGroup Condition="'$(_HasReferenceToSystemRuntime)' == 'true'">
-                       <!-- If the user has manually referenced these assemblies, remove them so we don't end up with duplicates -->
-                       <ReferencePath Remove="@(_DesignTimeFacadeAssemblies)"/>
-                       <ReferencePath Include="%(_DesignTimeFacadeAssemblies.Identity)">
-                               <WinMDFile>false</WinMDFile>
-                               <CopyLocal>false</CopyLocal>
-                               <ResolvedFrom>ImplicitlyExpandDesignTimeFacades</ResolvedFrom>
-                       </ReferencePath>
-                       <_ResolveAssemblyReferenceResolvedFiles Include="@(ReferencePath)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandDesignTimeFacades'" />
-               </ItemGroup>
-    
-               <Message Importance="Low" Text="Including @(ReferencePath)" Condition="'%(ReferencePath.ResolvedFrom)' == 'ImplicitlyExpandDesignTimeFacades'" />
-
-       </Target>
-       
-       <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportAfter\*"
-               Condition="'$(ImportByWildcardAfterMicrosoftCommonTargets)' == 'true' and Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\$(MSBuildThisFile)\ImportAfter')"/>
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.tasks b/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.tasks
deleted file mode 100644 (file)
index d326aad..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
-       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateCSharpManifestResourceName"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetReferenceAssemblyPaths"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/4.0/Microsoft.Portable.CSharp.targets b/mcs/tools/xbuild/xbuild/4.0/Microsoft.Portable.CSharp.targets
deleted file mode 100644 (file)
index d80a9f5..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <Import Project="$(MSBuildToolsPath)\Microsoft.Portable.CSharp.Targets" />    
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/4.5/FrameworkList.xml b/mcs/tools/xbuild/xbuild/4.5/FrameworkList.xml
deleted file mode 100644 (file)
index 2fa28c4..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<FileList  Name=".NET Framework 4.5" TargetFrameworkDirectory="..\..\..\..\4.5">
-</FileList>
diff --git a/mcs/tools/xbuild/xbuild/4.5/Microsoft.Portable.CSharp.targets b/mcs/tools/xbuild/xbuild/4.5/Microsoft.Portable.CSharp.targets
deleted file mode 100644 (file)
index d80a9f5..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <Import Project="$(MSBuildToolsPath)\Microsoft.Portable.CSharp.Targets" />    
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/FrameworkList-3.0.xml b/mcs/tools/xbuild/xbuild/FrameworkList-3.0.xml
deleted file mode 100644 (file)
index ae06c88..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<FileList Name=".NET Framework 3.0" TargetFrameworkDirectory="..\..\..\..\2.0">
-</FileList>
diff --git a/mcs/tools/xbuild/xbuild/MSBuild/Microsoft.Build.CommonTypes.xsd b/mcs/tools/xbuild/xbuild/MSBuild/Microsoft.Build.CommonTypes.xsd
deleted file mode 100644 (file)
index 390189b..0000000
+++ /dev/null
@@ -1,1581 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<xs:schema targetNamespace="http://schemas.microsoft.com/developer/msbuild/2003" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003"
-elementFormDefault="qualified">
-
-    <!-- =================== INCLUDE COMMON SCHEMA =========================== -->
-    <xs:include schemaLocation="Microsoft.Build.Core.xsd"/>
-    
-    <!-- ======================== ITEMS =====================================-->
-    <!-- Possible Types include SimpleItemType (no meta-data subelements), GenericItemType (any meta-data), or something more specific.-->
-    <xs:element name="Reference" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Reference to an assembly</xs:documentation>
-        </xs:annotation>
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="HintPath">
-                                <xs:annotation>
-                                    <xs:documentation>Relative or absolute path to the assembly (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="Name">
-                                <xs:annotation>
-                                    <xs:documentation>Friendly display name (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="FusionName">
-                                <xs:annotation>
-                                    <xs:documentation>Fusion name of the assembly (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                            
-                            <xs:element name="SpecificVersion">
-                                <xs:annotation>
-                                    <xs:documentation>Whether only the version in the fusion name should be referenced (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="Aliases">
-                                <xs:annotation>
-                                    <xs:documentation>Aliases for the reference (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="Private">
-                                <xs:annotation>
-                                    <xs:documentation>Whether the reference should be copied to the output folder (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                        </xs:choice>
-                    </xs:sequence>
-                    <!-- redefine Include just to give a specific description -->
-                    <xs:attribute name="Include" type="xs:string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>Assembly name or filename</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="COMReference" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Reference to a COM component</xs:documentation>
-        </xs:annotation>
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="Name">
-                                <xs:annotation>
-                                    <xs:documentation>Friendly display name (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="Guid">
-                                <xs:annotation>
-                                    <xs:documentation>GUID in the form {00000000-0000-0000-0000-000000000000}</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="VersionMajor">
-                                <xs:annotation>
-                                    <xs:documentation>Major part of the version number</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="VersionMinor">
-                                <xs:annotation>
-                                    <xs:documentation>Minor part of the version number</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="Lcid">
-                                <xs:annotation>
-                                    <xs:documentation>Locale ID</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="WrapperTool">
-                                <xs:annotation>
-                                    <xs:documentation>Wrapper tool, such as tlbimp</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="Isolated">
-                                <xs:annotation>
-                                    <xs:documentation>Is it isolated (boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                        </xs:choice>
-                    </xs:sequence>
-                    <!-- redefine Include just to give a specific description -->
-                    <xs:attribute name="Include" type="xs:string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>COM component name</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="COMFileReference" substitutionGroup="msb:Item">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="WrapperTool"/>
-                        </xs:choice>
-                    </xs:sequence>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="NativeReference" substitutionGroup="msb:Item">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="Name"/>
-                            <xs:element name="HintPath"/>
-                        </xs:choice>
-                    </xs:sequence>
-                    <!-- redefine Include just to give a specific description -->
-                    <xs:attribute name="Include" type="xs:string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>Path to native reference</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>                    
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ProjectReference" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Reference to another project</xs:documentation>
-        </xs:annotation>
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="Name">
-                                <xs:annotation>
-                                    <xs:documentation>Friendly display name (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="Project">
-                                <xs:annotation>
-                                    <xs:documentation>Project GUID, in the form {00000000-0000-0000-0000-000000000000}</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="Package"/>
-                        </xs:choice>
-                    </xs:sequence>
-                    <!-- redefine Include just to give a specific description -->
-                    <xs:attribute name="Include" type="xs:string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>Path to project file</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>    
-    <xs:element name="Compile" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Source files for compiler</xs:documentation>
-        </xs:annotation>        
-        <xs:complexType>           
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">                       
-                        <xs:choice>
-                            <xs:element name="SubType"/>
-                            <xs:element name="DependentUpon"/>
-                            <xs:element name="AutoGen">
-                                <xs:annotation>
-                                    <xs:documentation>Whether file was generated from another file (boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                 
-                            <xs:element name="DesignTime"/>
-                            <xs:element name="Link">
-                                <xs:annotation>
-                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="DesignTimeSharedInput"/>
-                            <xs:element name="InProject">
-                                <xs:annotation>
-                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                        </xs:choice>
-                    </xs:sequence>
-                    <!-- redefine Include just to give a specific description -->
-                    <xs:attribute name="Include" type="xs:string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>Semi-colon separated list of source files (wildcards are allowed)</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>                    
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="EmbeddedResource" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Resources to be embedded in the generated assembly</xs:documentation>
-        </xs:annotation>        
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="DependentUpon"/>
-                            <xs:element name="Generator">
-                                <xs:annotation>
-                                    <xs:documentation>Name of any file generator that is run on this item</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                               
-                            <xs:element name="LastGenOutput">
-                                <xs:annotation>
-                                    <xs:documentation>File that was created by any file generator that was run on this item</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                 
-                            <xs:element name="CustomToolNamespace">
-                                <xs:annotation>
-                                    <xs:documentation>Namespace into which any file generator that is run on this item should create code</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="Link">
-                                <xs:annotation>
-                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="InProject">
-                                <xs:annotation>
-                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="SubType"/>
-                        </xs:choice>
-                    </xs:sequence>
-                    <!-- redefine Include just to give a specific description -->
-                    <xs:attribute name="Include" type="xs:string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>Semi-colon separated list of resource files (wildcards are allowed)</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>                    
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Content" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Files that are not compiled, but may be embedded or published</xs:documentation>
-        </xs:annotation>
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="DependentUpon"/>
-                            <xs:element name="Generator">
-                                <xs:annotation>
-                                    <xs:documentation>Name of any file generator that is run on this item</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                  
-                            <xs:element name="LastGenOutput"/>
-                            <xs:element name="CustomToolNamespace"/>
-                            <xs:element name="Link">
-                                <xs:annotation>
-                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="Group"/>
-                            <xs:element name="PublishState">
-                            <xs:annotation>
-                                <xs:documentation>Default, Included, Excluded, DataFile, or Prerequisite</xs:documentation>
-                            </xs:annotation>
-                            </xs:element>
-                            <xs:element name="IsAssembly"/>
-                            <xs:element name="InProject">
-                                <xs:annotation>
-                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="SubType"/>
-                            <xs:element name="CopyToOutputDirectory">
-                                <xs:annotation>
-                                    <xs:documentation>Copy file to output directory (optional, boolean, default false)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                    
-                        </xs:choice>
-                    </xs:sequence>
-                    <!-- redefine Include just to give a specific description -->
-                    <xs:attribute name="Include" type="xs:string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>Semi-colon separated list of content files (wildcards are allowed)</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>    
-    <xs:element name="None" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Files that should have no role in the build process</xs:documentation>
-        </xs:annotation>
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <!-- UNDONE. Remove all but Link when #318721 is fixed-->
-                            <xs:element name="DependentUpon"/>
-                            <xs:element name="Generator">
-                                <xs:annotation>
-                                    <xs:documentation>Name of any file generator that is run on this item</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                  
-                            <xs:element name="LastGenOutput"/>
-                            <xs:element name="CustomToolNamespace"/>
-                            <xs:element name="Link">
-                                <xs:annotation>
-                                    <xs:documentation>Notional path within project to display if the file is physically located outside of the project file's cone (optional)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="InProject">
-                                <xs:annotation>
-                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                        </xs:choice>
-                    </xs:sequence>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Folder" type="msb:SimpleItemType" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Folder on disk</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="Import" type="msb:SimpleItemType" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Assemblies whose namespaces should be imported by the Visual Basic compiler</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="Service" type="msb:SimpleItemType" substitutionGroup="msb:Item"/>
-    <xs:element name="WebReferences" type="msb:SimpleItemType" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Name of Web References folder to display in user interface</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="WebReferenceUrl" substitutionGroup="msb:Item">
-        <xs:annotation>
-            <xs:documentation>Represents a reference to a web service</xs:documentation>
-        </xs:annotation>        
-            <xs:complexType>
-                <xs:complexContent>
-                    <xs:extension base="msb:SimpleItemType">
-                        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                            <xs:choice>
-                                <xs:element name="UrlBehavior"/>
-                                <xs:element name="RelPath"/>
-                                <xs:element name="UpdateFromURL"/>
-                                <xs:element name="ServiceLocationURL"/>
-                                <xs:element name="CachedDynamicPropName"/>
-                                <xs:element name="CachedAppSettingsObjectName"/>
-                                <xs:element name="CachedSettingsPropName"/>
-                            </xs:choice>
-                        </xs:sequence>
-                        <!-- redefine Include just to give a specific description -->
-                        <xs:attribute name="Include" type="xs:string" use="required">
-                            <xs:annotation>
-                                <xs:documentation>URL to web service</xs:documentation>
-                            </xs:annotation>
-                        </xs:attribute>                        
-                    </xs:extension>
-                </xs:complexContent>
-            </xs:complexType>
-    </xs:element>
-    <xs:element name="BootstrapperFile" substitutionGroup="msb:Item">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="InProject">
-                                <xs:annotation>
-                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="ProductName"/>
-                            <xs:element name="Install"/>
-                        </xs:choice>
-                    </xs:sequence>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="PublishFile" substitutionGroup="msb:Item">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                        <xs:choice>
-                            <xs:element name="InProject">
-                                <xs:annotation>
-                                    <xs:documentation>Display in user interface (optional, boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                                
-                            <xs:element name="Group"/>
-                            <xs:element name="IsAssembly">
-                                <xs:annotation>
-                                    <xs:documentation>(boolean)</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>
-                            <xs:element name="PublishState">
-                                <xs:annotation>
-                                    <xs:documentation>Default, Included, Excluded, DataFile, or Prerequisite</xs:documentation>
-                                </xs:annotation>
-                            </xs:element>                            
-                        </xs:choice>
-                    </xs:sequence>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <!-- ======================== PROPERTIES =====================================-->
-    <!-- Possible Types include StringPropertyType (text with no subelements), GenericPropertyType (any content), or something more specific.-->
-    <xs:element name="AllowUnsafeBlocks" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ApplicationIcon" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ApplicationRevision" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>integer</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="ApplicationVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Matches the expression "\d\.\d\.\d\.(\d|\*)"</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="AppDesignerFolder" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Name of folder for Application Designer</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="AssemblyKeyContainerName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="AssemblyKeyProviderName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="AssemblyName" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Name of output assembly</xs:documentation>
-        </xs:annotation>
-    </xs:element>           
-    <xs:element name="AssemblyOriginatorKeyFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="AssemblyOriginatorKeyFileType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="AssemblyOriginatorKeyMode" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="AssemblyType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="AutorunEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>         
-    <xs:element name="BaseAddress" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="BootstrapperComponentsLocation" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>HomeSite, Relative, or Absolute</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="BootstrapperComponentsUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="BootstrapperEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="CheckForOverflowUnderflow" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="CodePage" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="Configuration" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ConfigurationOverrideFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="CreateWebPageOnPublish" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="DebugSecurityZoneURL" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DebugSymbols" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Whether to emit symbols (boolean)</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="DebugType" type="msb:StringPropertyType" substitutionGroup="msb:Property">   
-        <xs:annotation>
-            <xs:documentation>none, pdbonly, or full</xs:documentation>
-        </xs:annotation>
-    </xs:element>         
-    <xs:element name="DefaultClientScript" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DefaultHTMLPageLayout" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DefaultTargetSchema" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DefineConstants" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DefineDebug" type="msb:StringPropertyType" substitutionGroup="msb:Property">   
-        <xs:annotation>
-            <xs:documentation>Whether DEBUG is defined (boolean)</xs:documentation>
-        </xs:annotation>
-    </xs:element>          
-    <xs:element name="DefineTrace" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Whether TRACE is defined (boolean)</xs:documentation>
-        </xs:annotation>
-    </xs:element>          
-    <xs:element name="DelaySign" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DisableLangXtns" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DisallowUrlActiviation" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="DeployDirSuffix" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="DocumentationFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="EnableASPDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="EnableASPXDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="EnableSQLServerDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="EnableSecurityDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="EnableUnmanagedDebugging" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ErrorReport" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ExcludedPermissions" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="FallbackCulture" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="FileAlignment" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="FileUpgradeFlags" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="FormFactorID" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="FxCopLogFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="FxCopProjectFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="FxCopRules" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="GenerateManifests" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="GenerateSerializationAssemblies" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="Install" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="InstallFrom" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Web, Unc, or Disk</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="InstallUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="IsWebBootstrapper" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="JCPA" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="LangVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ManifestCertificateThumbprint" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ManifestKeyFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="MapFileExtensions" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>                
-    <xs:element name="MinimumRequiredVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Matches the expression "\d\.\d\.\d\.\d"</xs:documentation>
-        </xs:annotation>
-    </xs:element>                
-    <xs:element name="MyType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="NoConfig" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>    
-    <xs:element name="NoStandardLibraries" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="NoStdLib" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Whether standard libraries (such as mscorlib) should be referenced automatically (boolean)</xs:documentation>
-        </xs:annotation>
-    </xs:element>          
-    <xs:element name="NoWarn" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Comma separated list of disabled warnings</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="OpenBrowserOnPublish" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>                
-    <xs:element name="Optimize" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Should compiler optimize output (boolean)</xs:documentation>
-        </xs:annotation>
-    </xs:element>     
-    <xs:element name="OptionCompare" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Option Compare setting (Text or Binary)</xs:documentation>
-        </xs:annotation>
-    </xs:element>         
-    <xs:element name="OptionExplicit" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Should Option Explicit be set (On or Off)</xs:documentation>
-        </xs:annotation>
-    </xs:element>         
-    <xs:element name="OptionStrict" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Should Option Strict be set (On or Off)</xs:documentation>
-        </xs:annotation>
-    </xs:element>            
-    <xs:element name="OSVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="OutputPath" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Path to output folder, with trailing slash</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="OutputType" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Type of output to generate (WinExe, Exe, or Library)</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="Platform" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="PlatformFamilyName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>    
-    <xs:element name="PlatformID" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>    
-    <xs:element name="PlatformTarget" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="PostBuildEvent" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Command line to be run at the end of build</xs:documentation>
-        </xs:annotation>
-    </xs:element>          
-    <xs:element name="PreBuildEvent" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Command line to be run at the start of build</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="ProductName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ProductVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ProjectGuid" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ProjectType" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ProjectTypeGuids" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="PublisherName" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="PublishUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="RecursePath" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ReferencePath" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Semi-colon separated list of folders to search during reference resolution</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="RegisterForComInterop" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="RemoteDebugEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="RemoteDebugMachine" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="RemoveIntegerChecks" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="ResponseFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="RootNamespace" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="RunFxCop" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="RunPostBuildEvent" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="SchemaVersion" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="SecureScoping" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="SignAssembly" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="SignManifests" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartAction" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartArguments" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartPage" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartProgram" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartURL" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartWithIE" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartWorkingDirectory" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="StartupObject" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Type that contains the main entry point</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="SupportUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="TargetCulture" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="TargetZone" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="TreatWarningsAsErrors" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="TrustUrlParameters" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>                
-    <xs:element name="TypeComplianceDiagnostics" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="UpdateEnabled" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>                
-    <xs:element name="UpdateInterval" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="UpdateIntervalUnits" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Hours, Days, or Weeks</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="UpdateMode" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Foreground or Background</xs:documentation>
-        </xs:annotation>
-    </xs:element>
-    <xs:element name="UpdatePeriodically" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="UpdateRequired" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>boolean</xs:documentation>
-        </xs:annotation>
-    </xs:element>                
-    <xs:element name="UpdateUrl" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>    
-    <xs:element name="UTF8OutPut" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="UseVSHostingProcess" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="VSTO_TrustAssembliesLocation" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="WarningLevel" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>integer between 0 and 4 inclusive</xs:documentation>
-        </xs:annotation>
-    </xs:element>        
-    <xs:element name="WarningsAsErrors" type="msb:StringPropertyType" substitutionGroup="msb:Property">
-        <xs:annotation>
-            <xs:documentation>Comma separated list of warning numbers to treat as errors</xs:documentation>
-        </xs:annotation>
-    </xs:element>          
-    <xs:element name="WebPage" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <xs:element name="Win32ResourceFile" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>
-    <!-- ======================== TASKS =====================================-->
-    <xs:element name="AL" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="OutputAssembly" use="required" />
-                    <xs:attribute name="AlgorithmId" />
-                    <xs:attribute name="BaseAddress" />
-                    <xs:attribute name="CompanyName" />
-                    <xs:attribute name="Configuration" />
-                    <xs:attribute name="Copyright" />
-                    <xs:attribute name="Culture" />
-                    <xs:attribute name="DelaySign" />
-                    <xs:attribute name="Description" />
-                    <xs:attribute name="EmbedResources" />
-                    <xs:attribute name="EvidenceFile" />
-                    <xs:attribute name="FileVersion" />
-                    <xs:attribute name="Flags" />
-                    <xs:attribute name="GenerateFullPaths" />
-                    <xs:attribute name="KeyContainer" />
-                    <xs:attribute name="KeyFile" />
-                    <xs:attribute name="LinkResources" />
-                    <xs:attribute name="MainEntryPoint" />
-                    <xs:attribute name="Platform" />
-                    <xs:attribute name="ProductName" />
-                    <xs:attribute name="ProductVersion" />
-                    <xs:attribute name="ResponseFiles" />
-                    <xs:attribute name="SourceModules" />
-                    <xs:attribute name="TargetType" />
-                    <xs:attribute name="TemplateFile" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="Title" />
-                    <xs:attribute name="ToolPath" />
-                    <xs:attribute name="Trademark" />
-                    <xs:attribute name="Version" />
-                    <xs:attribute name="Win32Icon" />
-                    <xs:attribute name="Win32Resource" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="AspNetCompiler" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Clean" />
-                    <xs:attribute name="Debug" />
-                    <xs:attribute name="Force" />
-                    <xs:attribute name="MetabasePath" />
-                    <xs:attribute name="PhysicalPath" />
-                    <xs:attribute name="TargetPath" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                    <xs:attribute name="Updateable" />
-                    <xs:attribute name="VirtualPath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="AssignCulture" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Files" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="AssignTargetPath" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="RootFolder" use="required" />
-                    <xs:attribute name="Files" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Copy" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="DestinationFiles" />
-                    <xs:attribute name="DestinationFolder" />
-                    <xs:attribute name="SkipUnchangedFiles" />
-                    <xs:attribute name="SourceFiles" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="CreateCSharpManifestResourceName" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="ResourceFiles" use="required" />
-                    <xs:attribute name="RootNamespace" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="CreateItem" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AdditionalMetadata" />
-                    <xs:attribute name="Exclude" />
-                    <xs:attribute name="Include" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="CreateJSharpManifestResourceName" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="ResourceFiles" use="required" />
-                    <xs:attribute name="RootNamespace" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="CreateProperty" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Value" />
-                    <xs:attribute name="ValueSetByTask" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="CreateVisualBasicManifestResourceName" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="ResourceFiles" use="required" />
-                    <xs:attribute name="RootNamespace" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Csc" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AdditionalLibPaths" />
-                    <xs:attribute name="AddModules" />
-                    <xs:attribute name="AllowUnsafeBlocks" />
-                    <xs:attribute name="BaseAddress" />
-                    <xs:attribute name="CheckForOverflowUnderflow" />
-                    <xs:attribute name="CodePage" />
-                    <xs:attribute name="DebugType" />
-                    <xs:attribute name="DefineConstants" />
-                    <xs:attribute name="DelaySign" />
-                    <xs:attribute name="DisabledWarnings" />
-                    <xs:attribute name="DocumentationFile" />
-                    <xs:attribute name="EmitDebugInformation" />
-                    <xs:attribute name="ErrorReport" />
-                    <xs:attribute name="FileAlignment" />
-                    <xs:attribute name="GenerateFullPaths" />
-                    <xs:attribute name="KeyContainer" />
-                    <xs:attribute name="KeyFile" />
-                    <xs:attribute name="LangVersion" />
-                    <xs:attribute name="LinkResources" />
-                    <xs:attribute name="MainEntryPoint" />
-                    <xs:attribute name="NoConfig" />
-                    <xs:attribute name="NoLogo" />
-                    <xs:attribute name="NoStandardLib" />
-                    <xs:attribute name="Optimize" />
-                    <xs:attribute name="OutputAssembly" />
-                    <xs:attribute name="Platform" />
-                    <xs:attribute name="References" />
-                    <xs:attribute name="Resources" />
-                    <xs:attribute name="ResponseFiles" />
-                    <xs:attribute name="Sources" />
-                    <xs:attribute name="TargetType" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                    <xs:attribute name="TreatWarningsAsErrors" />
-                    <xs:attribute name="UseHostCompilerIfAvailable" />
-                    <xs:attribute name="Utf8Output" />
-                    <xs:attribute name="WarningLevel" />
-                    <xs:attribute name="WarningsAsErrors" />
-                    <xs:attribute name="WarningsNotAsErrors" />
-                    <xs:attribute name="Win32Icon" />
-                    <xs:attribute name="Win32Resource" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Delete" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Files" use="required" />
-                    <xs:attribute name="DeletedFiles" />
-                    <xs:attribute name="TreatErrorsAsWarnings" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Error" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Text" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Exec" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Command" use="required" />
-                    <xs:attribute name="IgnoreExitCode" />
-                    <xs:attribute name="Outputs" />
-                    <xs:attribute name="StandardErrorEncoding" />
-                    <xs:attribute name="StandardOutputEncoding" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="WorkingDirectory" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="FindUnderPath" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Path" use="required" />
-                    <xs:attribute name="Files" />
-                    <xs:attribute name="InPath" />
-                    <xs:attribute name="OutOfPath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="FormatUrl" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="InputUrl" />
-                    <xs:attribute name="OutputUrl" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="FormatVersion" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="FormatType" />
-                    <xs:attribute name="OutputVersion" />
-                    <xs:attribute name="Revision" />
-                    <xs:attribute name="Version" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="FxCop" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="ApplyLogFileXsl" />
-                    <xs:attribute name="Assemblies" />
-                    <xs:attribute name="ConsoleXsl" />
-                    <xs:attribute name="DependentAssemblyPaths" />
-                    <xs:attribute name="Imports" />
-                    <xs:attribute name="LogFile" />
-                    <xs:attribute name="LogFileXsl" />
-                    <xs:attribute name="OutputToConsole" />
-                    <xs:attribute name="PlatformPath" />
-                    <xs:attribute name="Project" />
-                    <xs:attribute name="RuleAssemblies" />
-                    <xs:attribute name="Rules" />
-                    <xs:attribute name="Summary" />
-                    <xs:attribute name="ToolPath" />
-                    <xs:attribute name="UpdateProjectFile" />
-                    <xs:attribute name="Verbose" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GenerateApplicationManifest" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AssemblyName" />
-                    <xs:attribute name="AssemblyVersion" />
-                    <xs:attribute name="ClrVersion" />
-                    <xs:attribute name="ConfigFile" />
-                    <xs:attribute name="Dependencies" />
-                    <xs:attribute name="Description" />
-                    <xs:attribute name="EntryPoint" />
-                    <xs:attribute name="Files" />
-                    <xs:attribute name="IconFile" />
-                    <xs:attribute name="InputManifest" />
-                    <xs:attribute name="IsolatedComReferences" />
-                    <xs:attribute name="ManifestType" />
-                    <xs:attribute name="MaxTargetPath" />
-                    <xs:attribute name="OSVersion" />
-                    <xs:attribute name="OutputManifest" />
-                    <xs:attribute name="Platform" />
-                    <xs:attribute name="TargetCulture" />
-                    <xs:attribute name="TrustInfoFile" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GenerateBootstrapper" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="ApplicationFile" />
-                    <xs:attribute name="ApplicationName" />
-                    <xs:attribute name="ApplicationUrl" />
-                    <xs:attribute name="BootstrapperComponentFiles" />
-                    <xs:attribute name="BootstrapperItems" />
-                    <xs:attribute name="BootstrapperKeyFile" />
-                    <xs:attribute name="ComponentsLocation" />
-                    <xs:attribute name="ComponentsUrl" />
-                    <xs:attribute name="CopyComponents" />
-                    <xs:attribute name="Culture" />
-                    <xs:attribute name="FallbackCulture" />
-                    <xs:attribute name="OutputPath" />
-                    <xs:attribute name="Path" />
-                    <xs:attribute name="SupportUrl" />
-                    <xs:attribute name="Validate" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GenerateDeploymentManifest" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AssemblyName" />
-                    <xs:attribute name="AssemblyVersion" />
-                    <xs:attribute name="DeploymentUrl" />
-                    <xs:attribute name="Description" />
-                    <xs:attribute name="DisallowUrlActivation" />
-                    <xs:attribute name="EntryPoint" />
-                    <xs:attribute name="InputManifest" />
-                    <xs:attribute name="Install" />
-                    <xs:attribute name="MaxTargetPath" />
-                    <xs:attribute name="MapFileExtensions" />
-                    <xs:attribute name="MinimumRequiredVersion" />
-                    <xs:attribute name="OutputManifest" />
-                    <xs:attribute name="Platform" />
-                    <xs:attribute name="Product" />
-                    <xs:attribute name="Publisher" />
-                    <xs:attribute name="SupportUrl" />
-                    <xs:attribute name="TargetCulture" />
-                    <xs:attribute name="TrustUrlParameters" />
-                    <xs:attribute name="UpdateEnabled" />
-                    <xs:attribute name="UpdateInterval" />
-                    <xs:attribute name="UpdateMode" />
-                    <xs:attribute name="UpdateUnit" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GenerateResource" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Sources" use="required" />
-                    <xs:attribute name="FilesWritten" />
-                    <xs:attribute name="NeverLockTypeAssemblies" />
-                    <xs:attribute name="OutputResources" />
-                   <xs:attribute name="References" />
-                    <xs:attribute name="StateFile" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="UseSourcePath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GetAssemblyIdentity" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AssemblyFiles" use="required" />
-                    <xs:attribute name="Assemblies" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GetFrameworkPath" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Path" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GetFrameworkSdkPath" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Path" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GetLinkedFilesFromResX" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Sources" use="required" />
-                    <xs:attribute name="StateFile" />
-                    <xs:attribute name="UseSourcePath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="LC" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="LicenseTarget" use="required" />
-                    <xs:attribute name="Sources" use="required" />
-                    <xs:attribute name="NoLogo" />
-                    <xs:attribute name="OutputDirectory" />
-                    <xs:attribute name="OutputLicense" />
-                    <xs:attribute name="ReferencedAssemblies" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="MakeDir" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Directories" use="required" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Message" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Importance" />
-                    <xs:attribute name="Text" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="MSBuild" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Projects" use="required" />
-                    <xs:attribute name="RebaseOutputs" />
-                    <xs:attribute name="StopOnFirstFailure" />
-                    <xs:attribute name="RunEachTargetSeparately" />
-                    <xs:attribute name="Targets" />
-                    <xs:attribute name="Properties" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ReadLinesFromFile" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="File" use="required" />
-                    <xs:attribute name="Lines" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="RegisterAssembly" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Assemblies" use="required" />
-                    <xs:attribute name="CreateCodeBase" />
-                    <xs:attribute name="StateFile" />
-                    <xs:attribute name="TypeLibFiles" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="RemoveDir" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Directories" use="required" />
-                    <xs:attribute name="RemovedDirectories" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="RemoveDuplicates" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Filtered" />
-                    <xs:attribute name="Inputs" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ResGen" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Sources" use="required" />
-                    <xs:attribute name="FilesWritten" />
-                    <xs:attribute name="OutputResources" />
-                    <xs:attribute name="References" />
-                    <xs:attribute name="StateFile" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                    <xs:attribute name="UseSourcePath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ResolveAssemblyReference" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="SearchPaths" use="required" />
-                    <xs:attribute name="AppConfigFile" />
-                    <xs:attribute name="Assemblies" />
-                    <xs:attribute name="AssemblyFiles" />
-                    <xs:attribute name="AutoUnify" />
-                    <xs:attribute name="CandidateAssemblyFiles" />
-                    <xs:attribute name="FilesWritten" />
-                    <xs:attribute name="FindDependencies" />
-                    <xs:attribute name="FindRelatedFiles" />
-                    <xs:attribute name="FindSatellites" />
-                    <xs:attribute name="InstalledAssemblyTables" />
-                    <xs:attribute name="Silent" />
-                    <xs:attribute name="StateFile" />
-                    <xs:attribute name="TargetFrameworkDirectory" />
-                    <xs:attribute name="TargetProcessorArchitecture" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ResolveComReference" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="DelaySign" />
-                    <xs:attribute name="KeyContainer" />
-                    <xs:attribute name="KeyFile" />
-                    <xs:attribute name="NoClassMembers" />
-                    <xs:attribute name="ResolvedAssemblyReferences" />
-                    <xs:attribute name="ResolvedFiles" />
-                    <xs:attribute name="ResolvedModules" />
-                    <xs:attribute name="StateFile" />
-                    <xs:attribute name="TypeLibFiles" />
-                    <xs:attribute name="TypeLibNames" />
-                    <xs:attribute name="WrapperOutputDirectory" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ResolveKeySource" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AutoClosePasswordPromptShow" />
-                    <xs:attribute name="AutoClosePasswordPromptTimeout" />
-                    <xs:attribute name="CertificateFile" />
-                    <xs:attribute name="CertificateThumbprint" />
-                    <xs:attribute name="KeyFile" />
-                    <xs:attribute name="ResolvedKeyContainer" />
-                    <xs:attribute name="ResolvedKeyFile" />
-                    <xs:attribute name="ResolvedThumbprint" />
-                    <xs:attribute name="SuppressAutoClosePasswordPrompt" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="GenerateTrustInfo" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="BaseManifest" />
-                    <xs:attribute name="ExcludedPermissions" />
-                    <xs:attribute name="TargetZone" use="required" />
-                    <xs:attribute name="TrustInfoFile" use="required" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ResolveManifestFiles" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="EntryPoint" />
-                    <xs:attribute name="TrustInfoFile" />
-                    <xs:attribute name="Dependencies" /> <!-- obsolete -->
-                    <xs:attribute name="ExtraFiles" />
-                    <xs:attribute name="Files" />
-                    <xs:attribute name="ManagedAssemblies" />
-                    <xs:attribute name="NativeAssemblies" />
-                    <xs:attribute name="OutputAssemblies" />
-                    <xs:attribute name="OutputDependencies" /> <!-- obsolete -->
-                    <xs:attribute name="OutputFiles" />
-                    <xs:attribute name="OutputPrerequisites" /> <!-- obsolete -->
-                    <xs:attribute name="OutputSatellites" /> <!-- obsolete -->
-                    <xs:attribute name="PublishFiles" />
-                    <xs:attribute name="Satellites" /> <!-- obsolete -->
-                    <xs:attribute name="SatelliteAssemblies" />
-                    <xs:attribute name="TargetCulture" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ResolveNativeReference" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="NativeReferences" use="required" />
-                    <xs:attribute name="ContainedComComponents" />
-                    <xs:attribute name="ContainedLooseEtcFiles" />
-                    <xs:attribute name="ContainedLooseTlbFiles" />
-                    <xs:attribute name="ContainedNetAssemblies" />
-                    <xs:attribute name="ContainedTypeLibraries" />
-                    <xs:attribute name="ContainingReferenceFiles" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="ResolveVCProjectOutput" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="ProjectReferences" use="required" />
-                    <xs:attribute name="Configuration" />
-                    <xs:attribute name="PreresolvedVCOutputs" />
-                    <xs:attribute name="ResolvedOutputPaths" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="SGen" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="BuildAssemblyName" use="required" />
-                    <xs:attribute name="BuildAssemblyPath" use="required" />
-                    <xs:attribute name="ShouldGenerateSerializer" use="required" />
-                    <xs:attribute name="DelaySign" />
-                    <xs:attribute name="KeyContainer" />
-                    <xs:attribute name="KeyFile" />
-                    <xs:attribute name="References" />
-                    <xs:attribute name="SerializationAssembly" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="SignFile" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="CertificateThumbprint" use="required" />
-                    <xs:attribute name="SigningTarget" use="required" />
-                    <xs:attribute name="TimestampUrl" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Touch" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Files" use="required" />
-                    <xs:attribute name="AlwaysCreate" />
-                    <xs:attribute name="ForceTouch" />
-                    <xs:attribute name="Time" />
-                    <xs:attribute name="TouchedFiles" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="UnregisterAssembly" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Assemblies" />
-                    <xs:attribute name="StateFile" />
-                    <xs:attribute name="TypeLibFiles" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="UpdateManifest" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="InputManifest" use="required" />
-                    <xs:attribute name="ApplicationManifest" />
-                    <xs:attribute name="ApplicationPath" />
-                    <xs:attribute name="OutputManifest" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Vbc" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AdditionalLibPaths" />
-                    <xs:attribute name="AddModules" />
-                    <xs:attribute name="BaseAddress" />
-                    <xs:attribute name="CodePage" />
-                    <xs:attribute name="DebugType" />
-                    <xs:attribute name="DefineConstants" />
-                    <xs:attribute name="DelaySign" />
-                    <xs:attribute name="DisabledWarnings" />
-                    <xs:attribute name="DocumentationFile" />
-                    <xs:attribute name="EmitDebugInformation" />
-                    <xs:attribute name="ErrorReport" />
-                    <xs:attribute name="FileAlignment" />
-                    <xs:attribute name="GenerateDocumentation" />
-                    <xs:attribute name="Imports" />
-                    <xs:attribute name="KeyContainer" />
-                    <xs:attribute name="KeyFile" />
-                    <xs:attribute name="LinkResources" />
-                    <xs:attribute name="MainEntryPoint" />
-                    <xs:attribute name="NoConfig" />
-                    <xs:attribute name="NoLogo" />
-                    <xs:attribute name="NoStandardLib" />
-                    <xs:attribute name="NoWarnings" />
-                    <xs:attribute name="Optimize" />
-                    <xs:attribute name="OptionCompare" />
-                    <xs:attribute name="OptionExplicit" />
-                    <xs:attribute name="OptionStrict" />
-                    <xs:attribute name="OutputAssembly" />
-                    <xs:attribute name="Platform" />
-                    <xs:attribute name="References" />
-                    <xs:attribute name="RemoveIntegerChecks" />
-                    <xs:attribute name="Resources" />
-                    <xs:attribute name="ResponseFiles" />
-                    <xs:attribute name="RootNamespace" />
-                    <xs:attribute name="SdkPath" />
-                    <xs:attribute name="Sources" />
-                    <xs:attribute name="TargetCompactFramework" />
-                    <xs:attribute name="TargetType" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                    <xs:attribute name="TreatWarningsAsErrors" />
-                    <xs:attribute name="UseHostCompilerIfAvailable" />
-                    <xs:attribute name="Utf8Output" />
-                    <xs:attribute name="Verbosity" />
-                    <xs:attribute name="WarningsAsErrors" />
-                    <xs:attribute name="WarningsNotAsErrors" />
-                    <xs:attribute name="Win32Icon" />
-                    <xs:attribute name="Win32Resource" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="VCBuild" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Projects" use="required" />
-                    <xs:attribute name="Clean" />
-                    <xs:attribute name="Configuration" />
-                    <xs:attribute name="Override" />
-                    <xs:attribute name="Rebuild" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Vjc" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="AdditionalLibPaths" />
-                    <xs:attribute name="AddModules" />
-                    <xs:attribute name="BaseAddress" />
-                    <xs:attribute name="CodePage" />
-                    <xs:attribute name="DebugType" />
-                    <xs:attribute name="DefineConstants" />
-                    <xs:attribute name="DelaySign" />
-                    <xs:attribute name="DisabledWarnings" />
-                    <xs:attribute name="DisableExtensions" />
-                    <xs:attribute name="DocumentationFile" />
-                    <xs:attribute name="EmitDebugInformation" />
-                    <xs:attribute name="FileAlignment" />
-                    <xs:attribute name="Jcpa" />
-                    <xs:attribute name="KeyContainer" />
-                    <xs:attribute name="KeyFile" />
-                    <xs:attribute name="LinkResources" />
-                    <xs:attribute name="MainEntryPoint" />
-                    <xs:attribute name="NoConfig" />
-                    <xs:attribute name="NoLogo" />
-                    <xs:attribute name="Optimize" />
-                    <xs:attribute name="OutputAssembly" />
-                    <xs:attribute name="References" />
-                    <xs:attribute name="Resources" />
-                    <xs:attribute name="ResponseFiles" />
-                    <xs:attribute name="SecureScoping" />
-                    <xs:attribute name="Sources" />
-                    <xs:attribute name="TargetType" />
-                    <xs:attribute name="Timeout" />
-                    <xs:attribute name="ToolPath" />
-                    <xs:attribute name="TreatWarningsAsErrors" />
-                    <xs:attribute name="Utf8Output" />
-                    <xs:attribute name="WarningLevel" />
-                    <xs:attribute name="Win32Icon" />
-                    <xs:attribute name="Win32Resource" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="VjsResGen" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Sources" use="required" />
-                    <xs:attribute name="OutputResx" />
-                    <xs:attribute name="WildCards" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="Warning" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="Text" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-    <xs:element name="WriteLinesToFile" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="File" use="required" />
-                    <xs:attribute name="Lines" />
-                    <xs:attribute name="Overwrite" />
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>
-</xs:schema>
diff --git a/mcs/tools/xbuild/xbuild/MSBuild/Microsoft.Build.Core.xsd b/mcs/tools/xbuild/xbuild/MSBuild/Microsoft.Build.Core.xsd
deleted file mode 100644 (file)
index 9ab9bda..0000000
+++ /dev/null
@@ -1,390 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<xs:schema targetNamespace="http://schemas.microsoft.com/developer/msbuild/2003" xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
-    <!-- ======================================================================================= -->
-    <xs:element name="Project">
-        <xs:complexType>
-            <xs:sequence>
-                <xs:group ref="msb:ProjectLevelTagExceptTargetOrImportType" minOccurs="0" maxOccurs="unbounded"/>
-                <!-- must be at least one Target or Import tag-->
-                <xs:group ref="msb:TargetOrImportType"/>
-                <xs:group ref="msb:ProjectLevelTagType" minOccurs="0" maxOccurs="unbounded"/>
-            </xs:sequence>
-            <xs:attribute name="DefaultTargets" type="xs:string" use="optional">
-                <xs:annotation>
-                    <xs:documentation>Optional semi-colon separated list of one or more targets that will be built if no targets are otherwise specified</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-        </xs:complexType>
-    </xs:element>
-    <!-- ======================================================================================= -->
-    <xs:group name="ProjectLevelTagExceptTargetOrImportType">
-        <xs:choice>
-            <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
-            <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
-            <xs:element name="Choose" type="msb:ChooseType"/>
-            <xs:element name="Error" type="msb:WarningErrorOutsideTargetType">
-                <xs:annotation>
-                    <xs:documentation>Logs an Error event</xs:documentation>
-                </xs:annotation>
-            </xs:element>
-            <xs:element name="Warning" type="msb:WarningErrorOutsideTargetType">
-                <xs:annotation>
-                    <xs:documentation>Logs a Warning event</xs:documentation>
-                </xs:annotation>
-            </xs:element>
-            <xs:element name="Message" type="msb:MessageOutsideTargetType"/>
-            <xs:element name="UsingTask" type="msb:UsingTaskType"/>
-            <xs:element name="ProjectExtensions" type="msb:ProjectExtensionsType"/>
-        </xs:choice>
-    </xs:group>
-    <!-- ======================================================================================= -->    
-    <xs:group name="ProjectLevelTagType">
-        <xs:choice>
-            <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
-            <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
-            <xs:element name="Choose" type="msb:ChooseType"/>
-            <xs:element name="Error" type="msb:WarningErrorOutsideTargetType">
-                <xs:annotation>
-                    <xs:documentation>Logs an Error event</xs:documentation>
-                </xs:annotation>
-            </xs:element>                
-            <xs:element name="Warning" type="msb:WarningErrorOutsideTargetType">
-                <xs:annotation>
-                    <xs:documentation>Logs a Warning event</xs:documentation>
-                </xs:annotation>
-            </xs:element>                
-            <xs:element name="Message" type="msb:MessageOutsideTargetType"/>
-            <xs:element name="UsingTask" type="msb:UsingTaskType"/>
-            <xs:element name="Target" type="msb:TargetType"/>
-            <xs:element name="Import" type="msb:ImportType"/>
-            <xs:element name="ProjectExtensions" type="msb:ProjectExtensionsType"/>
-        </xs:choice>
-    </xs:group>
-    <!-- ======================================================================================= -->
-    <xs:group name="TargetOrImportType">
-        <xs:choice>
-            <xs:element name="Target" type="msb:TargetType"/>
-            <xs:element name="Import" type="msb:ImportType"/>
-        </xs:choice>
-    </xs:group>    
-    <!-- ======================================================================================= -->        
-    <xs:complexType name="TargetType">
-        <xs:annotation>
-            <xs:documentation>Groups tasks into a section of the build process</xs:documentation>
-        </xs:annotation>
-        <xs:sequence>
-            <xs:choice minOccurs="0" maxOccurs="unbounded">
-                <xs:element ref="msb:Task"/>
-            </xs:choice>
-            <xs:element name="OnError" type="msb:OnErrorType" minOccurs="0" maxOccurs="unbounded"/>
-            <!-- no elements are allowed under Target after an OnError element-->
-        </xs:sequence>
-        <xs:attribute name="Name" type="msb:non_empty_string" use="required">
-            <xs:annotation>
-                <xs:documentation>Name of the target</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-        <xs:attribute name="DependsOnTargets" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional semi-colon separated list of targets that should be run before this target</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>            
-        <xs:attribute name="Inputs" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional semi-colon separated list of files that form inputs into this target. Their timestamps will be compared with the timestamps of files in Outputs to determine whether the Target is up to date</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>                
-        <xs:attribute name="Outputs" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional semi-colon separated list of files that form outputs into this target. Their timestamps will be compared with the timestamps of files in Inputs to determine whether the Target is up to date</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the Target and the targets it depends on should be run</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>            
-    </xs:complexType>
-    <!-- ======================================================================================= -->        
-    <xs:complexType name="PropertyGroupType">
-        <xs:annotation>
-            <xs:documentation>Groups property definitions</xs:documentation>
-        </xs:annotation>
-        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-            <xs:element ref="msb:Property"/>
-        </xs:sequence>
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the PropertyGroup should be used</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>                
-    </xs:complexType>
-    <!-- ======================================================================================= -->        
-    <xs:complexType name="ItemGroupType">
-        <xs:annotation>
-            <xs:documentation>Groups item list definitions</xs:documentation>
-        </xs:annotation>        
-        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-            <xs:element ref="msb:Item"/>
-        </xs:sequence>
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the ItemGroup should be used</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>                
-    </xs:complexType>
-    <!-- ======================================================================================= -->
-    <xs:complexType name="ChooseType">
-        <xs:annotation>
-            <xs:documentation>Groups When and Otherwise elements</xs:documentation>
-        </xs:annotation>
-        <xs:sequence>
-            <xs:element name="When" type="msb:WhenType" maxOccurs="unbounded"/>
-            <xs:element name="Otherwise" type="msb:OtherwiseType" minOccurs="0"/>
-        </xs:sequence>
-    </xs:complexType>
-    <!-- ======================================================================================= -->
-    <xs:complexType name="WhenType">
-        <xs:annotation>
-            <xs:documentation>Groups PropertyGroup and/or ItemGroup elements</xs:documentation>
-        </xs:annotation>
-        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-            <xs:choice>
-                <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
-                <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
-                <xs:element name="Choose" type="msb:ChooseType"/>
-            </xs:choice>
-        </xs:sequence>
-        <xs:attribute name="Condition" type="xs:string" use="required">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the child PropertyGroups and/or ItemGroups should be used</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-    </xs:complexType>
-    <!-- ======================================================================================= -->
-    <xs:complexType name="OtherwiseType">
-        <xs:annotation>
-            <xs:documentation>Groups PropertyGroup and/or ItemGroup elements that are used if no Conditions on sibling When elements evaluate to true</xs:documentation>
-        </xs:annotation>        
-        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-            <xs:choice>
-                <xs:element name="PropertyGroup" type="msb:PropertyGroupType"/>
-                <xs:element name="ItemGroup" type="msb:ItemGroupType"/>
-                <xs:element name="Choose" type="msb:ChooseType"/>
-            </xs:choice>
-        </xs:sequence>
-    </xs:complexType>
-    <!-- ======================================================================================= -->        
-    <xs:complexType name="OnErrorType">
-        <xs:annotation>
-            <xs:documentation>Specifies targets to execute in the event of a recoverable error</xs:documentation>
-        </xs:annotation>
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the targets should be executed</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-        <xs:attribute name="ExecuteTargets" type="msb:non_empty_string" use="required">
-            <xs:annotation>
-                <xs:documentation>Semi-colon separated list of targets to execute</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>            
-    </xs:complexType>
-    <!-- ======================================================================================= -->        
-    <xs:complexType name="MessageOutsideTargetType">
-        <xs:annotation>
-            <xs:documentation>Logs an informational Message event, with an optional Importance</xs:documentation>
-        </xs:annotation>
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the Message should be logged</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>            
-        <xs:attribute name="Importance" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional priority level. Allowed values are Low, Normal (default), and High</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-        <xs:attribute name="Text" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Text to log</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-    </xs:complexType>
-    <!-- ======================================================================================= -->        
-    <xs:complexType name="WarningErrorOutsideTargetType">
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the text should be logged</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-        <xs:attribute name="Text" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Text to log</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-    </xs:complexType>    
-    <!-- ======================================================================================= -->    
-    <xs:complexType name="UsingTaskType">
-        <xs:annotation>
-            <xs:documentation>Declares where to load a task that will be used in the project</xs:documentation>
-        </xs:annotation>        
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the declaration should be evaluated</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>                
-        <xs:attribute name="AssemblyName" type="msb:non_empty_string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional name of assembly containing the task. Either AssemblyName or AssemblyFile must be used</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-        <xs:attribute name="AssemblyFile" type="msb:non_empty_string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional path to assembly containing the task. Either AssemblyName or AssemblyFile must be used</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>            
-        <xs:attribute name="TaskName" type="msb:non_empty_string" use="required">
-            <xs:annotation>
-                <xs:documentation>Name of task class in the assembly</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-    </xs:complexType>
-    <!-- ======================================================================================= -->  
-    <xs:complexType name="ImportType">
-        <xs:annotation>
-            <xs:documentation>Declares that the contents of another project file should be inserted at this location</xs:documentation>
-        </xs:annotation>        
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the import should occur</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>              
-        <xs:attribute name="Project" type="msb:non_empty_string" use="required">
-            <xs:annotation>
-                <xs:documentation>Project file to import</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>            
-    </xs:complexType>
-    <!-- ======================================================================================= -->  
-    <xs:complexType name="ProjectExtensionsType" mixed="true">
-        <xs:annotation>
-            <xs:documentation>Optional section used by MSBuild hosts, that may contain arbitrary XML content that is ignored by MSBuild itself</xs:documentation>
-        </xs:annotation>
-        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-            <xs:any processContents="skip"/>
-        </xs:sequence>
-    </xs:complexType>    
-    <!-- ======================================================================================= -->
-    <xs:element name="Item" type="msb:SimpleItemType" abstract="true"/>
-    <!-- ======================================================================================= -->   
-    <!-- convenience type for items that have no meta-data-->
-    <xs:complexType name="SimpleItemType">
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the items should be evaluated</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-        <xs:attribute name="Include" type="xs:string" use="required">
-            <xs:annotation>
-                <xs:documentation>Semi-colon separated list of files (wildcards are allowed) or other item names to include in this item list</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-        <xs:attribute name="Exclude" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Semi-colon separated list of files (wildcards are allowed) or other item names to exclude from the Include list</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>             
-    </xs:complexType>
-    <!-- ======================================================================================= -->      
-    <!-- general utility type allowing an item type to be defined but not its child meta-data-->
-    <xs:complexType name="GenericItemType">
-        <xs:complexContent>
-            <xs:extension base="msb:SimpleItemType">
-                <xs:sequence minOccurs="0" maxOccurs="unbounded">
-                    <xs:any namespace="##any" processContents="skip"/>  
-                </xs:sequence>      
-            </xs:extension>
-        </xs:complexContent>
-    </xs:complexType>
-    <!-- ======================================================================================= -->  
-    <!-- no type declared on this abstract element, so either a simple or complex type can be substituted for it.-->
-    <xs:element name="Property" abstract="true"/>
-    <!-- ======================================================================================= -->      
-    <!-- convenience type for properties that just want to allow text and no elements in them-->
-    <xs:complexType name="StringPropertyType">
-        <xs:simpleContent>
-            <xs:extension base="xs:string">
-                <xs:attribute name="Condition" type="xs:string" use="optional">
-                    <xs:annotation>
-                        <xs:documentation>Optional expression evaluated to determine whether the property should be evaluated</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-            </xs:extension>
-        </xs:simpleContent>
-    </xs:complexType>
-    <!-- ======================================================================================= -->      
-    <!-- general utility type allowing text and/or elements inside-->
-    <xs:complexType name="GenericPropertyType" mixed="true">
-        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-            <xs:any namespace="##any" processContents="skip"/>
-        </xs:sequence>
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the property should be evaluated</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-    </xs:complexType>
-    <!-- ======================================================================================= -->
-    <xs:element name="Task" type="msb:TaskType" abstract="true"/>
-    <!-- ======================================================================================= -->
-    <xs:complexType name="TaskType">
-        <xs:sequence minOccurs="0" maxOccurs="unbounded">
-            <xs:element name="Output">
-                <xs:annotation>
-                    <xs:documentation>Optional element specifying a specific task output to be gathered</xs:documentation>
-                </xs:annotation>
-                <xs:complexType>
-                    <xs:attribute name="TaskParameter" type="msb:non_empty_string" use="required">
-                        <xs:annotation>
-                            <xs:documentation>Task parameter to gather. Matches the name of a .NET Property on the task class that has an [Output] attribute</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                    <xs:attribute name="ItemName" type="msb:non_empty_string" use="optional">
-                        <xs:annotation>
-                            <xs:documentation>Optional name of an item list to put the gathered outputs into. Either ItemName or PropertyName must be specified</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                    <xs:attribute name="PropertyName" type="msb:non_empty_string" use="optional">
-                        <xs:annotation>
-                            <xs:documentation>Optional name of a property to put the gathered output into. Either PropertyName or ItemName must be specified</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                    <xs:attribute name="Condition" type="xs:string" use="optional">
-                        <xs:annotation>
-                            <xs:documentation>Optional expression evaluated to determine whether the output should be gathered</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-                </xs:complexType>
-            </xs:element>
-        </xs:sequence>
-        <xs:attribute name="Condition" type="xs:string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional expression evaluated to determine whether the task should be executed</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-        <xs:attribute name="ContinueOnError" type="msb:non_empty_string" use="optional">
-            <xs:annotation>
-                <xs:documentation>Optional boolean indicating whether a recoverable task error should be ignored. Default false</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>            
-        <!-- We don't need the anyAttribute here because other types deriving from this type will add the right attributes.-->
-    </xs:complexType>
-    <!-- ======================================================================================= -->  
-    <!-- XSD considers an empty-valued attribute to satisfy use="required", but we want it to have a non-empty value in most cases, hence this utility type. -->
-    <xs:simpleType name="non_empty_string">
-        <xs:restriction base="xs:string">
-            <xs:minLength value="1"/>
-        </xs:restriction>
-    </xs:simpleType>
-</xs:schema>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Build.xsd b/mcs/tools/xbuild/xbuild/Microsoft.Build.xsd
deleted file mode 100644 (file)
index 1cd971c..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<xs:schema targetNamespace="http://schemas.microsoft.com/developer/msbuild/2003" 
-xmlns:xs="http://www.w3.org/2001/XMLSchema"
-xmlns:msb="http://schemas.microsoft.com/developer/msbuild/2003"
-elementFormDefault="qualified">
-
-    <!-- =================== IMPORT COMMON SCHEMA =========================== -->
-    <xs:include schemaLocation="MSBuild/Microsoft.Build.CommonTypes.xsd"/>
-
-    <!-- ========= ADD CUSTOM ITEMS, PROPERTIES, AND TASKS BELOW ======= -->
-    <!-- Note that these will be in the msbuild namespace. A future version of
-        msbuild may require that custom itemtypes, properties, and tasks be in a 
-        custom namespace, but currently msbuild only supports the msbuild namespace. -->
-    
-    <!-- example custom itemtype with particular meta-data required-->
-    <!--<xs:element name="MyItem" substitutionGroup="msb:Item">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:SimpleItemType">
-                    <xs:sequence maxOccurs="1">
-                        <xs:choice>
-                            <xs:element name="MyMetaData" type="xs:string"/>
-                        </xs:choice>
-                    </xs:sequence>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>-->
-    
-    <!-- Example custom itemtype with NO meta-data -->
-    <!--<xs:element name="MySimpleItem" type="msb:SimpleItemType" substitutionGroup="msb:Item"/>-->
-    
-    <!-- Example custom itemtype with ANY meta-data -->
-    <!--<xs:element name="MyFlexibleItem" type="msb:GenericItemType" substitutionGroup="msb:Item"/>-->
-
-    <!-- example custom property that allows string content only-->
-    <!--<xs:element name="MySimpleProperty" type="msb:StringPropertyType" substitutionGroup="msb:Property"/>-->
-
-    <!-- example custom task with single required parameter-->
-    <!--<xs:element name="MyTask" substitutionGroup="msb:Task">
-        <xs:complexType>
-            <xs:complexContent>
-                <xs:extension base="msb:TaskType">
-                    <xs:attribute name="MyParameter" type="xs:boolean" use="required"/>
-                </xs:extension>
-            </xs:complexContent>
-        </xs:complexType>
-    </xs:element>-->
-    
-</xs:schema>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets b/mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets
deleted file mode 100644 (file)
index 3c37825..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <PropertyGroup>
-               <DefaultLanguageSourceExtension>.cs</DefaultLanguageSourceExtension>
-               <Language>C#</Language>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <DebugSymbols Condition=" '$(DebugType)' == 'none' ">false</DebugSymbols>
-               <DebugType    Condition=" '$(DebugType)' == 'none' "></DebugType>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <CreateManifestResourceNamesDependsOn></CreateManifestResourceNamesDependsOn>
-               <CoreCompileDependsOn></CoreCompileDependsOn>
-
-               <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildToolsPath)\Microsoft.CSharp.targets</MSBuildAllProjects>
-       </PropertyGroup>
-
-       <ItemGroup>
-               <DocFileItem Include="$(DocumentationFile)" Condition="'$(DocumentationFile)' != ''"/>
-       </ItemGroup>
-
-       <Target
-               Name="CoreCompile"
-               Inputs="$(MSBuildAllProjects);@(Compile);@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile);
-                       $(KeyOriginatorFile);@(ReferencePath);$(Win32Icon);$(Win32Resource)"
-               Outputs="@(DocFileItem);@(IntermediateAssembly)"
-               DependsOnTargets="$(CoreCompileDependsOn)"
-       >
-               <Csc
-                       AdditionalLibPaths="$(AdditionalLibPaths)"
-                       AddModules="@(AddModules)"
-                       AllowUnsafeBlocks="$(AllowUnsafeBlocks)"
-                       BaseAddress="$(BaseAddress)"
-                       CheckForOverflowUnderflow="$(CheckForOverflowUnderflow)"
-                       CodePage="$(CodePage)"
-                       DebugType="$(DebugType)"
-                       DefineConstants="$(DefineConstants)"
-                       DelaySign="$(DelaySign)"
-                       DisabledWarnings="$(NoWarn)"
-                       DocumentationFile="@(DocFileItem)"
-                       EmitDebugInformation="$(DebugSymbols)"
-                       ErrorReport="$(ErrorReport)"
-                       FileAlignment="$(FileAlignment)"
-                       GenerateFullPaths="$(GenerateFullPaths)"
-                       KeyContainer="$(KeyContainerName)"
-                       KeyFile="$(KeyOriginatorFile)"
-                       LangVersion="$(LangVersion)"
-                       MainEntryPoint="$(StartupObject)"
-                       ModuleAssemblyName="$(ModuleAssemblyName)"
-                       NoConfig="true"
-                       NoLogo="$(NoLogo)"
-                       NoStandardLib="$(NoStdLib)"
-                       Optimize="$(Optimize)"
-                       OutputAssembly="@(IntermediateAssembly)"
-                       PdbFile="$(PdbFile)" 
-                       Platform="$(PlatformTarget)"
-                       References="@(ReferencePath)"
-                       ResponseFiles="$(CompilerResponseFile)"
-                       Sources="@(Compile)"
-                       TargetType="$(OutputType)"
-                       TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
-                       UseHostCompilerIfAvailable="$(UseHostCompilerIfAvailable)"
-                       Utf8Output="$(Utf8Output)"
-                       WarningLevel="$(WarningLevel)"
-                       WarningsAsErrors="$(WarningsAsErrors)"
-                       WarningsNotAsErrors="$(WarningsNotAsErrors)"
-                       Win32Icon="$(Win32Icon)"
-                       Win32Resource="$(Win32Resource)"
-                       Resources="@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile)"
-                       ToolExe="$(CscToolExe)"
-                       ToolPath="$(CscToolPath)" />
-
-       </Target>
-
-       <Target Name="CreateManifestResourceNames">
-               <CreateCSharpManifestResourceName Condition="'@(ResxWithNoCulture)' != ''"
-                       ResourceFiles="@(ResxWithNoCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithNoCultureName" />
-               </CreateCSharpManifestResourceName>
-
-               <CreateCSharpManifestResourceName Condition="'@(NonResxWithNoCulture)' != ''"
-                       ResourceFiles="@(NonResxWithNoCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithNoCulture" />
-               </CreateCSharpManifestResourceName>
-
-               <CreateCSharpManifestResourceName Condition="'@(ResxWithCulture)' != ''"
-                       ResourceFiles="@(ResxWithCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithCultureName" />
-               </CreateCSharpManifestResourceName>
-
-               <CreateCSharpManifestResourceName Condition="'@(NonResxWithCulture)' != ''"
-                       ResourceFiles="@(NonResxWithCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithCulture" />
-               </CreateCSharpManifestResourceName>
-       </Target>
-
-       <Import Project="Microsoft.Common.targets" />
-
-       <PropertyGroup>
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v4.5' and '$(OS)' != 'Windows_NT'">gmcs</CscToolExe>
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v4.5' and '$(OS)' == 'Windows_NT'">gmcs.bat</CscToolExe>
-
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.5' and '$(OS)' != 'Windows_NT'">mcs</CscToolExe>
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.5' and '$(OS)' == 'Windows_NT'">mcs.bat</CscToolExe>
-               
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' != 'Windows_NT'">dmcs</CscToolExe>
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' == 'Windows_NT'">dmcs.bat</CscToolExe>
-       </PropertyGroup>
-       
-       <PropertyGroup>
-               <TargetFrameworkMonikerAssemblyAttributeText Condition="'$(TargetFrameworkMoniker)' != '' and '$(TargetingClr2Framework)' != 'true'">
-// &lt;autogenerated /&gt;
-[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(&quot;$(TargetFrameworkMoniker)&quot;, FrameworkDisplayName = &quot;$(TargetFrameworkMonikerDisplayName)&quot;)]
-               </TargetFrameworkMonikerAssemblyAttributeText>
-       </PropertyGroup>
-
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Portable.CSharp.targets b/mcs/tools/xbuild/xbuild/Microsoft.Portable.CSharp.targets
deleted file mode 100644 (file)
index 72c20ef..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-
-       <PropertyGroup>
-               <AvailablePlatforms>Any CPU</AvailablePlatforms>
-
-               <TargetPlatformIdentifier>Portable</TargetPlatformIdentifier>
-               <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
-               <TargetFrameworkMonikerDisplayName>.NET Portable Subset</TargetFrameworkMonikerDisplayName>
-
-               <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
-               <NoStdLib>true</NoStdLib>
-
-               <ImplicitlyExpandTargetFramework Condition="'$(ImplicitlyExpandTargetFramework)' == '' ">true</ImplicitlyExpandTargetFramework> 
-       </PropertyGroup>
-
-       <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.Targets" />
-       
-       <PropertyGroup>
-               <ResolveReferencesDependsOn>
-                       $(ResolveReferencesDependsOn);
-                       ImplicitlyExpandTargetFramework;
-               </ResolveReferencesDependsOn>
-               
-               <ImplicitlyExpandTargetFrameworkDependsOn>
-                       $(ImplicitlyExpandTargetFrameworkDependsOn);
-                       GetReferenceAssemblyPaths
-               </ImplicitlyExpandTargetFrameworkDependsOn>
-       </PropertyGroup>
-       
-       <Target Name="ImplicitlyExpandTargetFramework"
-               DependsOnTargets="$(ImplicitlyExpandTargetFrameworkDependsOn)">
-
-               <ItemGroup>
-                       <ReferenceAssemblyPaths Include="$(_TargetFrameworkDirectories)"/>
-                       <ReferencePath Include="%(ReferenceAssemblyPaths.Identity)\*.dll">
-                               <CopyLocal>false</CopyLocal>
-                               <ResolvedFrom>ImplicitlyExpandTargetFramework</ResolvedFrom>
-                               <IsSystemReference>True</IsSystemReference>
-                       </ReferencePath>
-               </ItemGroup>
-       </Target>
-
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.CSharp.targets b/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.CSharp.targets
deleted file mode 100644 (file)
index 7aff37d..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-       <Import Project="Microsoft.Silverlight.Common.targets"/>
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.Common.targets b/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.Common.targets
deleted file mode 100644 (file)
index 55eacf1..0000000
+++ /dev/null
@@ -1,159 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <UsingTask TaskName="Moonlight.Build.Tasks.CreateTestPage" AssemblyFile="Moonlight.Build.Tasks.dll" />
-       <UsingTask TaskName="Moonlight.Build.Tasks.GenerateMoonlightManifest" AssemblyFile="Moonlight.Build.Tasks.dll"/>
-       <UsingTask TaskName="Moonlight.Build.Tasks.GenerateXap" AssemblyFile="Moonlight.Build.Tasks.dll" />
-       <UsingTask TaskName="Moonlight.Build.Tasks.GetMoonlightFrameworkPath" AssemblyFile="Moonlight.Build.Tasks.dll"/>
-       <UsingTask TaskName="Moonlight.Build.Tasks.Respack" AssemblyFile="Moonlight.Build.Tasks.dll" />
-       <UsingTask TaskName="Moonlight.Build.Tasks.XamlG" AssemblyFile="Moonlight.Build.Tasks.dll"/>
-
-       <PropertyGroup>
-               <PrepareResourcesDependsOn>
-                       GenerateXamlG;
-                       Respack;
-                       $(PrepareResourcesDependsOn)
-               </PrepareResourcesDependsOn>
-
-               <PrepareForRunDependsOn>
-                       GenerateMoonlightManifest;
-                       GenerateXap;
-                       CreateTestPage;
-                       $(PrepareForRunDependsOn)
-               </PrepareForRunDependsOn>
-
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(OS)' == 'Windows_NT'">smcs.bat</CscToolExe>
-               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(OS)' != 'Windows_NT'">smcs</CscToolExe>
-
-               <XapFileName Condition="'$(XapFileName)' == ''">$(AssemblyName).xap</XapFileName>
-               <TestPageFileName Condition="'$(TestPageFileName)' == ''">TestPage.html</TestPageFileName>
-               <SilverlightVersion Condition="'$(SilverlightVersion)' == ''">@SILVERLIGHT_VERSION@</SilverlightVersion>
-               <RuntimeVersion Condition="'$(RuntimeVersion)' == '' and '$(SilverlightVersion)' == '2.0'">2.0.31005.0</RuntimeVersion>
-               <RuntimeVersion Condition="'$(RuntimeVersion)' == '' and '$(SilverlightVersion)' == '3.0'">3.0.40624.0</RuntimeVersion>
-
-               <AssemblySearchPaths>
-                       {CandidateAssemblyFiles};
-                       $(ReferencePath);
-                       {HintPathFromItem};
-                       {TargetFrameworkDirectory};
-                       {RawFileName};
-                       $(OutDir)
-               </AssemblySearchPaths>
-       </PropertyGroup>
-
-       <ItemGroup>
-               <MoonlightManifestFile Include="$(OutDir)AppManifest.xaml">
-                       <TargetPath>AppManifest.xaml</TargetPath>
-               </MoonlightManifestFile>
-       </ItemGroup>
-
-       <!-- Override 'GetFrameworkPaths' -->
-       <Target Name="GetFrameworkPaths">
-               <GetMoonlightFrameworkPath
-                       SilverlightVersion="$(SilverlightVersion)">
-                       <Output TaskParameter="FrameworkPath" PropertyName="TargetFrameworkDirectory"/>
-                       <Output TaskParameter="FrameworkPath" ItemName="_FrameworkPath"/>
-               </GetMoonlightFrameworkPath>
-
-               <Error Text="Moonlight framework v$(SilverlightVersion) doesn't seem to be installed. Expected framework directory could not be found (@(_FrameworkPath)). To force a particular silverlight version, try: xbuild $(MSBuildProjectFile) /p:SilverlightVersion=2.0"
-                       Condition="!Exists('@(_FrameworkPath)')" />
-
-               <CreateProperty Value="$(AssemblySearchPaths);@(_FrameworkPath->'%(Identity)-redist')"
-                               Condition="Exists('@(_FrameworkPath->'%(Identity)-redist')')">
-                       <Output TaskParameter="Value" PropertyName="AssemblySearchPaths"/>
-               </CreateProperty>
-       </Target>
-
-       <Target Name="Respack">
-               <Respack
-                       Resources="@(Resource);@(Page);@(ApplicationDefinition)"
-                       OutputFile="$(IntermediateOutputPath)$(AssemblyName).g.resources">
-                       <Output TaskParameter="OutputFile" ItemName="FileWrites"/>
-                       <Output TaskParameter="OutputFile" ItemName="ManifestResourceWithNoCulture"/>
-               </Respack>
-       </Target>
-
-       <Target Name="GenerateXamlG">
-               <CreateItem Include="@(Compile)" Condition="'%(Compile.Extension)' == '.xaml' and '%(Compile.Generator)' == 'MSBuild:MarkupCompilePass1'">
-                       <Output TaskParameter="Include" ItemName="XamlFiles"/>
-               </CreateItem>
-               <CreateItem Include="@(ApplicationDefinition)" Condition="'%(Extension)' == '.xaml' and '%(Generator)' == 'MSBuild:MarkupCompilePass1'">
-                       <Output TaskParameter="Include" ItemName="XamlFiles"/>
-               </CreateItem>
-               <CreateItem Include="@(Page)" Condition="'%(Extension)' == '.xaml' and '%(Generator)' == 'MSBuild:MarkupCompilePass1'">
-                       <Output TaskParameter="Include" ItemName="XamlFiles"/>
-               </CreateItem>
-
-               <XamlG
-                       Sources="@(XamlFiles)"
-                       Language = "$(Language)"
-                       AssemblyName = "$(AssemblyName)"
-                       OutputFiles = "@(XamlFiles->'$(IntermediateOutputPath)%(Filename).g$(DefaultLanguageSourceExtension)')"
-               >
-                       <Output TaskParameter="OutputFiles" ItemName="Compile"/>
-                       <Output TaskParameter="OutputFiles" ItemName="FileWrites"/>
-               </XamlG>
-       </Target>
-
-       <Target Name="GenerateMoonlightManifest"
-               Inputs="$(MSBuildAllProjects);$(SilverlightManifestTemplate)"
-               Outputs="@(MoonlightManifestFile->'%(Identity)')">
-               <GenerateMoonlightManifest
-                       ManifestFile="@(MoonlightManifestFile->'%(Identity)')"
-                       EntryPointAssembly="$(AssemblyName)$(TargetExt)"
-                       References="@(ReferenceCopyLocalPaths)"
-                       SilverlightManifestTemplate="$(SilverlightManifestTemplate)"
-                       SilverlightAppEntry="$(SilverlightAppEntry)"
-                       RuntimeVersion="$(RuntimeVersion)"
-
-                       Condition = "'$(GenerateSilverlightManifest)' == 'true'"
-               >
-                       <Output TaskParameter="ManifestFile" ItemName="FileWrites"/>
-               </GenerateMoonlightManifest>
-       </Target>
-
-       <PropertyGroup>
-               <GenerateXapDependsOn>
-                       GenerateXamlG;
-                       GenerateMoonlightManifest;
-                       GetXapInputFiles
-               </GenerateXapDependsOn>
-       </PropertyGroup>
-       <Target Name="GenerateXap" DependsOnTargets="$(GenerateXapDependsOn)" Condition="'$(XapOutputs)' == 'true'"
-               Inputs="@(XapInputFiles)" Outputs="$(OutDir)$(XapFilename)">
-               <!-- Looks for %(DestinationSubdirectory) in LocalCopyReferences -->
-               <GenerateXap
-                       InputFiles="@(XapInputFiles)"
-                       LocalCopyReferences="@(ReferenceCopyLocalPaths)"
-                       XapFilename="$(OutDir)$(XapFilename)"
-               >
-                       <Output TaskParameter="XapFilename" ItemName="FileWrites"/>
-               </GenerateXap>
-       </Target>
-
-       <Target Name="CreateTestPage" Condition="'$(CreateTestPage)' == 'true' and '$(XapOutputs)' == 'true'">
-               <CreateTestPage
-                       XapFileName="$(XapFileName)"
-                       Title="$(AssemblyName)"
-                       TestPageFilename="$(OutDir)$(TestPageFilename)">
-                       <Output TaskParameter="TestPageFilename" ItemName="FileWrites"/>
-               </CreateTestPage>
-       </Target>
-
-       <Target Name="GetXapInputFiles">
-               <CreateItem Include="@(IntermediateAssembly)" AdditionalMetadata="TargetPath=$(AssemblyName)$(TargetExt)">
-                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ContentWithTargetPath)">
-                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
-               </CreateItem>
-
-               <CreateItem Include="@(MoonlightManifestFile)" Condition="'$(GenerateSilverlightManifest)' == 'true'">
-                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
-               </CreateItem>
-
-               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb" AdditionalMetadata="TargetPath=$(AssemblyName)$(TargetExt).mdb"
-                               Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
-                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
-               </CreateItem>
-       </Target>
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.VisualBasic.targets b/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.VisualBasic.targets
deleted file mode 100644 (file)
index 262754f..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
-       <Import Project="Microsoft.Silverlight.Common.targets"/>
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.VisualBasic.targets b/mcs/tools/xbuild/xbuild/Microsoft.VisualBasic.targets
deleted file mode 100644 (file)
index 4b89dfa..0000000
+++ /dev/null
@@ -1,123 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateVisualBasicManifestResourceName" AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
-       <PropertyGroup>
-               <DefaultLanguageSourceExtension>.vb</DefaultLanguageSourceExtension>
-               <Language>VB</Language>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <CreateManifestResourceNamesDependsOn></CreateManifestResourceNamesDependsOn>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <FinalDefineConstants>CONFIG=&quot;$(Configuration)&quot;</FinalDefineConstants>
-               <FinalDefineConstants Condition=" '$(DefineDebug)' == 'true' ">$(FinalDefineConstants),DEBUG=-1</FinalDefineConstants>
-               <FinalDefineConstants Condition=" '$(DefineTrace)' == 'true' ">$(FinalDefineConstants),TRACE=-1</FinalDefineConstants>
-               <FinalDefineConstants Condition=" '$(MyType)' != '' ">$(FinalDefineConstants),_MyType=&quot;$(MyType)&quot;</FinalDefineConstants>
-               <FinalDefineConstants Condition=" '$(Platform)' != '' ">$(FinalDefineConstants),PLATFORM=&quot;$(Platform)&quot;</FinalDefineConstants>
-               <FinalDefineConstants Condition=" '$(Platform)' == '' ">$(FinalDefineConstants),PLATFORM=&quot;AnyCPU&quot;</FinalDefineConstants>
-               <FinalDefineConstants Condition=" '$(DefineConstants)' != '' ">$(FinalDefineConstants),$(DefineConstants)</FinalDefineConstants>
-
-               <_NoWarnings Condition=" '$(WarningLevel)' == '0' ">true</_NoWarnings>
-               <_NoWarnings Condition=" '$(WarningLevel)' == '1' ">false</_NoWarnings>
-
-               <DebugSymbols Condition=" '$(DebugType)' == 'none' ">false</DebugSymbols>
-               <DebugType    Condition=" '$(DebugType)' == 'none' "></DebugType>
-
-               <CoreCompileDependsOn></CoreCompileDependsOn>
-       </PropertyGroup>
-
-       <ItemGroup>
-               <DocFileItem Include="$(DocumentationFile)"  Condition="'$(DocumentationFile)'!=''"/>
-       </ItemGroup>
-
-       <Target
-               Name="CoreCompile"
-               Inputs="$(MSBuildAllProjects);@(Compile);@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile);@(DocFileItem);
-                       $(KeyOriginatorFile);@(ReferencePath);$(Win32Icon);$(Win32Resource)"
-               Outputs="@(IntermediateAssembly)"
-               DependsOnTargets="$(CoreCompileDependsOn)"
-       >
-               <Vbc
-                       AdditionalLibPaths="$(AdditionalLibPaths)"
-                       AddModules="@(AddModules)"
-                       BaseAddress="$(BaseAddress)"
-                       CodePage="$(CodePage)"
-                       DebugType="$(DebugType)"
-                       DefineConstants="$(FinalDefineConstants)"
-                       DelaySign="$(DelaySign)"
-                       DisabledWarnings="$(NoWarn)"
-                       DocumentationFile="@(DocFileItem)"
-                       EmitDebugInformation="$(DebugSymbols)"
-                       ErrorReport="$(ErrorReport)"
-                       FileAlignment="$(FileAlignment)"
-                       GenerateDocumentation="$(GenerateDocumentation)"
-                       Imports="@(Import)"
-                       KeyContainer="$(KeyContainerName)"
-                       KeyFile="$(KeyOriginatorFile)"
-                       MainEntryPoint="$(StartupObject)"
-                       NoConfig="true"
-                       NoLogo="$(NoLogo)"
-                       NoStandardLib="$(NoStdLib)"
-                       NoWarnings="$(_NoWarnings)"
-                       Optimize="$(Optimize)"
-                       OptionCompare="$(OptionCompare)"
-                       OptionExplicit="$(OptionExplicit)"
-                       OptionStrict="$(OptionStrict)"
-                       OptionStrictType="$(OptionStrictType)" 
-                       OutputAssembly="@(IntermediateAssembly)"
-                       Platform="$(PlatformTarget)"
-                       References="@(ResolvedFiles)"
-                       RemoveIntegerChecks="$(RemoveIntegerChecks)"
-                       Resources="@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile)"
-                       ResponseFiles="$(CompilerResponseFile)"
-                       RootNamespace="$(RootNamespace)"
-                       Sources="@(Compile)"
-                       TargetType="$(OutputType)"
-                       TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
-                       UseHostCompilerIfAvailable="$(UseHostCompilerIfAvailable)"
-                       Utf8Output="$(Utf8Output)"
-                       Verbosity="$(VbcVerbosity)"
-                       WarningsAsErrors="$(WarningsAsErrors)"
-                       WarningsNotAsErrors="$(WarningsNotAsErrors)"
-                       Win32Icon="$(Win32Icon)"
-                       Win32Resource="$(Win32Resource)"
-                       ToolExe="$(VbcToolExe)"
-                       ToolPath="$(VbcToolPath)"
-                       />
-
-       </Target>
-
-       <Target Name="CreateManifestResourceNames">
-               <CreateVisualBasicManifestResourceName Condition="'@(ResxWithNoCulture)' != ''"
-                       ResourceFiles="@(ResxWithNoCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithNoCultureName" />
-               </CreateVisualBasicManifestResourceName>
-
-               <CreateVisualBasicManifestResourceName Condition="'@(NonResxWithNoCulture)' != ''"
-                       ResourceFiles="@(NonResxWithNoCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithNoCulture" />
-               </CreateVisualBasicManifestResourceName>
-
-               <CreateVisualBasicManifestResourceName Condition="'@(ResxWithCulture)' != ''"
-                       ResourceFiles="@(ResxWithCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestResourceWithCultureName" />
-               </CreateVisualBasicManifestResourceName>
-
-               <CreateVisualBasicManifestResourceName Condition="'@(NonResxWithCulture)' != ''"
-                       ResourceFiles="@(NonResxWithCulture)" RootNamespace="$(RootNamespace)">
-                       <Output TaskParameter = "ManifestResourceNames" ItemName = "ManifestNonResxWithCulture" />
-               </CreateVisualBasicManifestResourceName>
-       </Target>
-
-       <Import Project="Microsoft.Common.targets" />
-
-       <PropertyGroup>
-               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' != 'Windows_NT'">vbnc2</VbcToolExe>
-               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' != 'v4.0' and '$(OS)' == 'Windows_NT'">vbnc2.bat</VbcToolExe>
-
-               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' != 'Windows_NT'">vbnc</VbcToolExe>
-               <VbcToolExe Condition="'$(VbcToolExe)' == '' and '$(TargetFrameworkVersion)' == 'v4.0' and '$(OS)' == 'Windows_NT'">vbnc.bat</VbcToolExe>
-       </PropertyGroup>
-
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.WebApplication.targets b/mcs/tools/xbuild/xbuild/Microsoft.WebApplication.targets
deleted file mode 100644 (file)
index 0f61904..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-       <PropertyGroup>
-               <WebApplicationOutputDir Condition="'$(OutDir)' != '$(OutputPath)'">$(OutDir)_PublishedWebsites\$(MSBuildProjectName)</WebApplicationOutputDir>
-
-               <PrepareForRunDependsOn>
-                       $(PrepareForRunDependsOn);
-                       _CopyWebApplication
-               </PrepareForRunDependsOn>
-       </PropertyGroup>
-
-       <!-- OutDir has been overridden, so copy all the relevant files to that -->
-       <Target Name="_CopyWebApplication" Condition="'$(OutDir)' != '$(OutputPath)'">
-               <MakeDir Directories="$(WebApplicationOutputDir)\bin"/>
-               <Copy SourceFiles="@(IntermediateAssembly)" DestinationFolder="$(WebApplicationOutputDir)\bin" SkipUnchangedFiles="true"/>
-               <Copy
-                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
-                       DestinationFolder="$(WebApplicationOutputDir)\bin"
-                       SkipUnchangedFiles="true" />
-
-               <Copy
-                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
-                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(WebApplicationOutputDir)\bin\%(Culture)\$(AssemblyName).resources.dll')"
-                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
-                       SkipUnchangedFiles="true" />
-
-               <!-- Copy the referenced assemblies -->
-               <Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(WebApplicationOutputDir)\bin" SkipUnchangedFiles="true" />
-               <Copy SourceFiles="@(Content)" DestinationFolder="$(WebApplicationOutputDir)\%(Content.RelativeDir)" />
-       </Target>
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/xbuild.rsp b/mcs/tools/xbuild/xbuild/xbuild.rsp
deleted file mode 100644 (file)
index 9b9ce70..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-# xbuild command line options specified here will be used
-# by xbuild on every build, unless /noautoresponse is passed
-# on the command line.
diff --git a/mcs/tools/xbuild/xbuild_targets.make b/mcs/tools/xbuild/xbuild_targets.make
deleted file mode 100644 (file)
index 8c3c998..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-test-local: copy-targets
-
-copy-targets:
-       for p in net_2_0 net_3_5 net_4_0; do \
-               cp $(XBUILD_DIR)/xbuild/Microsoft.CSharp.targets $(topdir)/class/lib/$$p; \
-               cp $(XBUILD_DIR)/xbuild/Microsoft.VisualBasic.targets $(topdir)/class/lib/$$p; \
-               cp $(XBUILD_DIR)/xbuild/Microsoft.Silverlight*.targets $(topdir)/class/lib/$$p; \
-       done
-       cp $(XBUILD_DIR)/xbuild/2.0/Microsoft.Common.* $(topdir)/class/lib/net_2_0
-       cp $(XBUILD_DIR)/xbuild/3.5/Microsoft.Common.* $(topdir)/class/lib/net_3_5
-       cp $(XBUILD_DIR)/xbuild/4.0/Microsoft.Common.* $(topdir)/class/lib/net_4_0
-
-clean-local: clean-target-files
-
-clean-target-files:
-       for p in net_2_0 net_3_5 net_4_0; do \
-               rm -f $(topdir)/class/lib/$$p/Microsoft.Common.targets; \
-               rm -f $(topdir)/class/lib/$$p/Microsoft.CSharp.targets; \
-               rm -f $(topdir)/class/lib/$$p/Microsoft.VisualBasic.targets; \
-               rm -f $(topdir)/class/lib/$$p/Microsoft.Silverlight*.targets; \
-               rm -f $(topdir)/class/lib/$$p/Microsoft.Common.tasks; \
-       done
diff --git a/mcs/tools/xbuild/xbuild_test.make b/mcs/tools/xbuild/xbuild_test.make
new file mode 100644 (file)
index 0000000..52c402b
--- /dev/null
@@ -0,0 +1,96 @@
+XBUILD_DATA_DIR=$(topdir)/tools/xbuild/data
+XBUILD_PROFILE_DIR=$(topdir)/class/lib/$(PROFILE)
+
+# makes xbuild look in the class/lib/$PROFILE build directories for targets etc
+export TESTING_MONO=a
+
+ifeq (4.0, $(FRAMEWORK_VERSION))
+NO_TEST=true
+else
+test-local: copy-targets $(test_lib).config
+clean-local: clean-targets clean-test-config
+endif
+
+xbuild-net4-fail:
+       @echo "The net_4_0 profile contains reference assemblies only and cannot be installed/tested as an xbuild toolset"
+       @exit 1
+
+$(test_lib).config: $(XBUILD_DATA_DIR)/xbuild.exe.config.in
+       sed -e 's/@ASM_VERSION@/$(XBUILD_ASSEMBLY_VERSION)/g' $(XBUILD_DATA_DIR)/xbuild.exe.config.in > $(test_lib).config
+
+clean-test-config:
+       rm -f $(test_lib).config
+
+copy-targets: copy-targets-$(XBUILD_VERSION)
+
+clean-targets: clean-targets-$(XBUILD_VERSION)
+
+XBUILD_2_0_PROFILE_DIR=$(topdir)/class/lib/net_2_0
+XBUILD_3_5_PROFILE_DIR=$(topdir)/class/lib/net_3_5
+XBUILD_4_0_PROFILE_DIR=$(topdir)/class/lib/net_4_5
+XBUILD_12_0_PROFILE_DIR=$(topdir)/class/lib/xbuild_12
+
+copy-targets-2.0:
+       cp $(XBUILD_DATA_DIR)/2.0/Microsoft.Common.targets $(XBUILD_2_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/2.0/Microsoft.Common.tasks $(XBUILD_2_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.CSharp.targets $(XBUILD_2_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.VisualBasic.targets $(XBUILD_2_0_PROFILE_DIR)
+
+copy-targets-3.5:
+       cp $(XBUILD_DATA_DIR)/3.5/Microsoft.Common.targets $(XBUILD_3_5_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/3.5/Microsoft.Common.tasks $(XBUILD_3_5_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.CSharp.targets $(XBUILD_3_5_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.VisualBasic.targets $(XBUILD_3_5_PROFILE_DIR)
+
+copy-targets-4.0:
+       cp $(XBUILD_DATA_DIR)/4.0/Microsoft.Common.targets $(XBUILD_4_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/4.0/Microsoft.Common.tasks $(XBUILD_4_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.CSharp.targets $(XBUILD_4_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.VisualBasic.targets $(XBUILD_4_0_PROFILE_DIR)
+
+copy-targets-12.0:
+       cp $(XBUILD_DATA_DIR)/12.0/Microsoft.Common.targets $(XBUILD_12_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/12.0/Microsoft.Common.tasks $(XBUILD_12_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.CSharp.targets $(XBUILD_12_0_PROFILE_DIR)
+       cp $(XBUILD_DATA_DIR)/Microsoft.VisualBasic.targets $(XBUILD_12_0_PROFILE_DIR)
+
+clean-targets-2.0:
+       rm -f $(XBUILD_2_0_PROFILE_DIR)/Microsoft.Common.targets
+       rm -f $(XBUILD_2_0_PROFILE_DIR)/Microsoft.Common.tasks
+       rm -f $(XBUILD_2_0_PROFILE_DIR)/Microsoft.CSharp.targets
+       rm -f $(XBUILD_2_0_PROFILE_DIR)/Microsoft.VisualBasic.targets
+
+clean-targets-3.5:
+       rm -f $(XBUILD_3_5_PROFILE_DIR)/Microsoft.Common.targets
+       rm -f $(XBUILD_3_5_PROFILE_DIR)/Microsoft.Common.tasks
+       rm -f $(XBUILD_3_5_PROFILE_DIR)/Microsoft.CSharp.targets
+       rm -f $(XBUILD_3_5_PROFILE_DIR)/Microsoft.VisualBasic.targets
+
+clean-targets-4.0:
+       rm -f $(XBUILD_4_0_PROFILE_DIR)/Microsoft.Common.targets
+       rm -f $(XBUILD_4_0_PROFILE_DIR)/Microsoft.Common.tasks
+       rm -f $(XBUILD_4_0_PROFILE_DIR)/Microsoft.CSharp.targets
+       rm -f $(XBUILD_4_0_PROFILE_DIR)/Microsoft.VisualBasic.targets
+
+clean-targets-12.0:
+       rm -f $(XBUILD_12_0_PROFILE_DIR)/Microsoft.Common.targets
+       rm -f $(XBUILD_12_0_PROFILE_DIR)/Microsoft.Common.tasks
+       rm -f $(XBUILD_12_0_PROFILE_DIR)/Microsoft.CSharp.targets
+       rm -f $(XBUILD_12_0_PROFILE_DIR)/Microsoft.VisualBasic.targets
+
+#allow tests to find older versions of libs and targets
+ifneq (2.0, $(XBUILD_VERSION))
+TEST_MONO_PATH := $(topdir)/class/lib/net_2_0
+copy-targets: copy-targets-2.0
+clean-targets: clean-targets-2.0
+ifneq (3.5, $(XBUILD_VERSION))
+TEST_MONO_PATH := $(topdir)/class/lib/net_3_5$(PLATFORM_PATH_SEPARATOR)$(TEST_MONO_PATH)
+copy-targets: copy-targets-3.5
+clean-targets: clean-targets-3.5
+ifneq (4.0, $(XBUILD_VERSION))
+TEST_MONO_PATH := $(topdir)/class/lib/net_4_5$(PLATFORM_PATH_SEPARATOR)$(TEST_MONO_PATH)
+copy-targets: copy-targets-4.0
+clean-targets: clean-targets-4.0
+endif
+endif
+endif
index 579c48dd89ed4fbd4cf3af2c99aecb7ac8e90307..b67a9ca9b706d13f9cfe010554b3c759a04dbe86 100755 (executable)
@@ -240,6 +240,43 @@ static void io_ops_init (void)
 /* Some utility functions.
  */
 
+/*
+ * Check if a file is writable by the current user.
+ *
+ * This is is a best effort kind of thing. It assumes a reasonable sane set
+ * of permissions by the underlying OS.
+ *
+ * We assume that basic unix permission bits are authoritative. Which might not
+ * be the case under systems with extended permissions systems (posix ACLs, SELinux, OSX/iOS sandboxing, etc)
+ *
+ * The choice of access as the fallback is due to the expected lower overhead compared to trying to open the file.
+ *
+ * The only expected problem with using access are for root, setuid or setgid programs as access is not consistent
+ * under those situations. It's to be expected that this should not happen in practice as those bits are very dangerous
+ * and should not be used with a dynamic runtime.
+ */
+static gboolean
+is_file_writable (struct stat *st, const char *path)
+{
+       /* Is it globally writable? */
+       if (st->st_mode & S_IWOTH)
+               return 1;
+
+       /* Am I the owner? */
+       if ((st->st_uid == geteuid ()) && (st->st_mode & S_IWUSR))
+               return 1;
+
+       /* Am I in the same group? */
+       if ((st->st_gid == getegid ()) && (st->st_mode & S_IWGRP))
+               return 1;
+
+       /* Fallback to using access(2). It's not ideal as it might not take into consideration euid/egid
+        * but it's the only sane option we have on unix.
+        */
+       return access (path, W_OK) == 0;
+}
+
+
 static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
                                              struct stat *buf,
                                              struct stat *lbuf)
@@ -259,14 +296,14 @@ static guint32 _wapi_stat_to_file_attributes (const gchar *pathname,
 
        if (S_ISDIR (buf->st_mode)) {
                attrs = FILE_ATTRIBUTE_DIRECTORY;
-               if (!(buf->st_mode & S_IWUSR)) {
+               if (!is_file_writable (buf, pathname)) {
                        attrs |= FILE_ATTRIBUTE_READONLY;
                }
                if (filename[0] == '.') {
                        attrs |= FILE_ATTRIBUTE_HIDDEN;
                }
        } else {
-               if (!(buf->st_mode & S_IWUSR)) {
+               if (!is_file_writable (buf, pathname)) {
                        attrs = FILE_ATTRIBUTE_READONLY;
 
                        if (filename[0] == '.') {
@@ -523,7 +560,7 @@ static guint32 file_seek(gpointer handle, gint32 movedistance,
 {
        struct _WapiHandle_file *file_handle;
        gboolean ok;
-       off_t offset, newpos;
+       gint64 offset, newpos;
        int whence, fd;
        guint32 ret;
        
@@ -578,15 +615,15 @@ static guint32 file_seek(gpointer handle, gint32 movedistance,
        offset=movedistance;
 #endif
 
-#ifdef HAVE_LARGE_FILE_SUPPORT
        DEBUG ("%s: moving handle %p by %lld bytes from %d", __func__,
-                 handle, offset, whence);
-#else
-       DEBUG ("%s: moving handle %p fd %d by %ld bytes from %d", __func__,
-                 handle, offset, whence);
-#endif
+                  handle, (long long)offset, whence);
 
+#ifdef PLATFORM_ANDROID
+       /* bionic doesn't support -D_FILE_OFFSET_BITS=64 */
+       newpos=lseek64(fd, offset, whence);
+#else
        newpos=lseek(fd, offset, whence);
+#endif
        if(newpos==-1) {
                DEBUG("%s: lseek on handle %p returned error %s",
                          __func__, handle, strerror(errno));
@@ -595,11 +632,7 @@ static guint32 file_seek(gpointer handle, gint32 movedistance,
                return(INVALID_SET_FILE_POINTER);
        }
 
-#ifdef HAVE_LARGE_FILE_SUPPORT
        DEBUG ("%s: lseek returns %lld", __func__, newpos);
-#else
-       DEBUG ("%s: lseek returns %ld", __func__, newpos);
-#endif
 
 #ifdef HAVE_LARGE_FILE_SUPPORT
        ret=newpos & 0xFFFFFFFF;
@@ -1362,6 +1395,43 @@ static gboolean share_allows_open (struct stat *statbuf, guint32 sharemode,
        return(TRUE);
 }
 
+
+static gboolean
+share_allows_delete (struct stat *statbuf, struct _WapiFileShare **share_info)
+{
+       gboolean file_already_shared;
+       guint32 file_existing_share, file_existing_access;
+
+       file_already_shared = _wapi_handle_get_or_set_share (statbuf->st_dev, statbuf->st_ino, FILE_SHARE_DELETE, GENERIC_READ, &file_existing_share, &file_existing_access, share_info);
+
+       if (file_already_shared) {
+               /* The reference to this share info was incremented
+                * when we looked it up, so be careful to put it back
+                * if we conclude we can't use this file.
+                */
+               if (file_existing_share == 0) {
+                       /* Quick and easy, no possibility to share */
+                       DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing = NONE", __func__, fileaccess);
+
+                       _wapi_handle_share_release (*share_info);
+
+                       return(FALSE);
+               }
+
+               if (!(file_existing_share & FILE_SHARE_DELETE)) {
+                       /* New access mode doesn't match up */
+                       DEBUG ("%s: Share mode prevents open: requested access: 0x%x, file has sharing: 0x%x", __func__, fileaccess, file_existing_share);
+
+                       _wapi_handle_share_release (*share_info);
+
+                       return(FALSE);
+               }
+       } else {
+               DEBUG ("%s: New file!", __func__);
+       }
+
+       return(TRUE);
+}
 static gboolean share_check (struct stat *statbuf, guint32 sharemode,
                             guint32 fileaccess,
                             struct _WapiFileShare **share_info, int fd)
@@ -1744,15 +1814,14 @@ gboolean MoveFile (const gunichar2 *name, const gunichar2 *dest_name)
                }
        }
 
-       /* Check to make sure sharing allows us to open the file for
-        * writing.  See bug 377049.
+       /* Check to make that we have delete sharing permission.
+        * See https://bugzilla.xamarin.com/show_bug.cgi?id=17009
         *
         * Do the checks that don't need an open file descriptor, for
         * simplicity's sake.  If we really have to do the full checks
         * then we can implement that later.
         */
-       if (share_allows_open (&stat_src, 0, GENERIC_WRITE,
-                              &shareinfo) == FALSE) {
+       if (share_allows_delete (&stat_src, &shareinfo) == FALSE) {
                SetLastError (ERROR_SHARING_VIOLATION);
                return FALSE;
        }
@@ -2013,7 +2082,7 @@ ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFile
                      const gunichar2 *backupFileName, guint32 replaceFlags, 
                      gpointer exclude, gpointer reserved)
 {
-       int result, errno_copy, backup_fd = -1,replaced_fd = -1;
+       int result, backup_fd = -1,replaced_fd = -1;
        gchar *utf8_replacedFileName, *utf8_replacementFileName = NULL, *utf8_backupFileName = NULL;
        struct stat stBackup;
        gboolean ret = FALSE;
@@ -2031,13 +2100,11 @@ ReplaceFile (const gunichar2 *replacedFileName, const gunichar2 *replacementFile
                // Open the backup file for read so we can restore the file if an error occurs.
                backup_fd = _wapi_open (utf8_backupFileName, O_RDONLY, 0);
                result = _wapi_rename (utf8_replacedFileName, utf8_backupFileName);
-               errno_copy = errno;
                if (result == -1)
                        goto replace_cleanup;
        }
 
        result = _wapi_rename (utf8_replacementFileName, utf8_replacedFileName);
-       errno_copy = errno;
        if (result == -1) {
                _wapi_set_last_path_error_from_errno (NULL, utf8_replacementFileName);
                _wapi_rename (utf8_backupFileName, utf8_replacedFileName);
index 6cf55aca06838bd8a93e63e8aecd2be11a1b7e6c..98012283ad3fb96011d99675e380b7229de48dd2 100644 (file)
@@ -1384,8 +1384,10 @@ gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
 
                        if (err == 0) 
                                done = TRUE;
-                       else
+                       else {
                                free (result);
+                               result = NULL;
+                       }
                }
        } while (err == 0 && !done);
        
@@ -1708,9 +1710,7 @@ static GSList *load_modules (void)
                const struct section *sec;
 #endif
                const char *name;
-               intptr_t slide;
 
-               slide = _dyld_get_image_vmaddr_slide (i);
                name = _dyld_get_image_name (i);
 #if SIZEOF_VOID_P == 8
                hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
index 27ee96d4e3cbeba0b137e8d18d12033a1a3a7f53..6f8fdd50c4b653afafe310a21b374d298592bb78 100644 (file)
@@ -778,7 +778,10 @@ int _wapi_setsockopt(guint32 fd, int level, int optname,
        gpointer handle = GUINT_TO_POINTER (fd);
        int ret;
        const void *tmp_val;
+#if defined (__linux__)
+       /* This has its address taken so it cannot be moved to the if block which uses it */
        int bufsize = 0;
+#endif
        struct timeval tv;
        
        if (startup_count == 0) {
index 1c62618c8128c69712d301a40e178fcc5af648d0..45ac431c3e9fb97ad3d93032f0a21afdb7654a97 100644 (file)
@@ -34,7 +34,6 @@ struct _WapiHandle_thread
        WapiThreadState state : 2;
        guint joined : 1;
        guint has_apc : 1;
-       guint32 create_flags;
        /* Fields below this point are only valid for the owning process */
        pthread_t id;
        GPtrArray *owned_mutexes;
@@ -46,7 +45,6 @@ struct _WapiHandle_thread
         * This also acts as a reference for the handle.
         */
        gpointer wait_handle;
-       MonoSemType suspend_sem;
        guint32 (*start_routine)(gpointer arg);
        gpointer start_arg;
 };
index 12b7c0c5d9c9f088deed2e88795930dbb5bb610d..bf59c7f27d5596ad65b1453da3564e7c4605600f 100644 (file)
@@ -40,31 +40,20 @@ G_BEGIN_DECLS
 typedef guint32 (*WapiThreadStart)(gpointer);
 typedef guint32 (*WapiApcProc)(gpointer);
 
-/* 
- * The 'tid' argument has a different type than in win32, which breaks on win64.
- * Runtime code shouldn't use this, use the mono_thread_create () function in
- * metadata instead.
- */
-extern gpointer CreateThread(WapiSecurityAttributes *security,
-                            guint32 stacksize, WapiThreadStart start,
-                            gpointer param, guint32 create, gsize *tid); /* NB tid is 32bit in MS API */
 extern gpointer OpenThread (guint32 access, gboolean inherit, gsize tid); /* NB tid is 32bit in MS API */
 extern void ExitThread(guint32 exitcode) G_GNUC_NORETURN;
 extern gboolean GetExitCodeThread(gpointer handle, guint32 *exitcode);
 extern gsize GetCurrentThreadId(void); /* NB return is 32bit in MS API */
 extern gpointer GetCurrentThread(void);
-extern guint32 ResumeThread(gpointer handle);
-extern guint32 SuspendThread(gpointer handle);
 extern void Sleep(guint32 ms);
 extern guint32 SleepEx(guint32 ms, gboolean alertable);
-extern guint32 QueueUserAPC (WapiApcProc apc_callback, gpointer thread_handle, 
-                                       gpointer param);
 
 /* Kludge alert! Making this visible outside io-layer is broken, but I
  * can't find any w32 call that will let me do this.
  */
 extern void _wapi_thread_signal_self (guint32 exitstatus);
 
+void wapi_thread_interrupt_self (void);
 void wapi_interrupt_thread (gpointer handle);
 void wapi_clear_interruption (void);
 gboolean wapi_thread_set_wait_handle (gpointer handle);
@@ -77,5 +66,8 @@ void wapi_finish_interrupt_thread (gpointer wait_handle);
 
 char* wapi_current_thread_desc (void);
 
+gpointer wapi_create_thread_handle (void);
+void wapi_thread_set_exit_code (guint32 exitstatus, gpointer handle);
+
 G_END_DECLS
 #endif /* _WAPI_THREADS_H_ */
index e623d71ce3142f7d6b6136fab960c61802f45631..54cba41ad12bb3bfa0e495fbf318beb0e5f31c3e 100644 (file)
@@ -165,7 +165,6 @@ void _wapi_thread_set_termination_details (gpointer handle,
        
        thread_handle->exitstatus = exitstatus;
        thread_handle->state = THREAD_STATE_EXITED;
-       MONO_SEM_DESTROY (&thread_handle->suspend_sem);
        g_ptr_array_free (thread_handle->owned_mutexes, TRUE);
 
        _wapi_handle_set_signal_state (handle, TRUE, TRUE);
@@ -214,6 +213,12 @@ static void thread_exit (guint32 exitstatus, gpointer handle)
        mono_gc_pthread_exit (NULL);
 }
 
+void
+wapi_thread_set_exit_code (guint32 exitstatus, gpointer handle)
+{
+       _wapi_thread_set_termination_details (handle, exitstatus);
+}
+
 static void thread_attached_exit (gpointer handle)
 {
        /* Drop the extra reference we take in thread_attach, now this
@@ -235,227 +240,53 @@ static void thread_hash_init(void)
        g_assert (thr_ret == 0);
 }
 
-static void _wapi_thread_suspend (struct _WapiHandle_thread *thread)
-{
-       g_assert (pthread_equal (thread->id, pthread_self ()));
-       
-       while (MONO_SEM_WAIT (&thread->suspend_sem) != 0 &&
-              errno == EINTR);
-}
-
-static void _wapi_thread_resume (struct _WapiHandle_thread *thread)
-{
-       MONO_SEM_POST (&thread->suspend_sem);
-}
-
-static void *thread_start_routine (gpointer args) G_GNUC_NORETURN;
-static void *thread_start_routine (gpointer args)
-{
-       struct _WapiHandle_thread *thread = (struct _WapiHandle_thread *)args;
-       int thr_ret;
-
-       if (!(thread->create_flags & CREATE_NO_DETACH)) {
-               thr_ret = mono_gc_pthread_detach (pthread_self ());
-               g_assert (thr_ret == 0);
-       }
-
-       thr_ret = pthread_setspecific (thread_hash_key,
-                                      (void *)thread->handle);
-       if (thr_ret != 0) {
-               /* This is only supposed to happen when Mono is
-                  shutting down.  We cannot assert on it, though,
-                  because we must not depend on metadata, which is
-                  where the shutdown code is.
-
-                  This is a race condition which arises because
-                  pthreads don't allow creation of suspended threads.
-                  Once Mono is set to shut down no new thread is
-                  allowed to start, even though threads may still be
-                  created.  We emulate suspended threads in this
-                  function by calling _wapi_thread_suspend() below.
-
-                  So it can happen that even though Mono is already
-                  shutting down we still end up here, and at this
-                  point the thread_hash_key might already be
-                  destroyed. */
-               mono_gc_pthread_exit (NULL);
-       }
-
-       DEBUG ("%s: started thread id %ld", __func__, thread->id);
-
-       /* We set it again here since passing &thread->id to pthread_create is racy
-          as the thread can start running before the value is set.*/
-       thread->id = pthread_self ();
-
-       if (thread->create_flags & CREATE_SUSPENDED) {
-               _wapi_thread_suspend (thread);
-       }
-       
-       thread_exit (thread->start_routine (thread->start_arg),
-                    thread->handle);
-
-#ifndef __GNUC__
-       /* Even though we tell gcc that this function doesn't return,
-        * other compilers won't see that.
-        */
-       return(NULL);
-#endif
-}
-
-/**
- * CreateThread:
- * @security: Ignored for now.
- * @stacksize: the size in bytes of the new thread's stack. Use 0 to
- * default to the normal stack size. (Ignored for now).
- * @start: The function that the new thread should start with
- * @param: The parameter to give to @start.
- * @create: If 0, the new thread is ready to run immediately.  If
- * %CREATE_SUSPENDED, the new thread will be in the suspended state,
- * requiring a ResumeThread() call to continue running.
- * @tid: If non-NULL, the ID of the new thread is stored here.  NB
- * this is defined as a DWORD (ie 32bit) in the MS API, but we need to
- * cope with 64 bit IDs for s390x and amd64.
- *
- * Creates a new threading handle.
+/*
+ * wapi_create_thread_handle:
  *
- * Return value: a new handle, or NULL
+ *   Create a thread handle for the current thread.
  */
-gpointer CreateThread(WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 stacksize,
-                     WapiThreadStart start, gpointer param, guint32 create,
-                     gsize *tid) 
+gpointer
+wapi_create_thread_handle (void)
 {
-       struct _WapiHandle_thread thread_handle = {0}, *thread_handle_p;
-       pthread_attr_t attr;
+       struct _WapiHandle_thread thread_handle = {0}, *thread;
        gpointer handle;
-       gboolean ok;
-       int ret;
-       int thr_ret;
-       int i, unrefs = 0;
-       gpointer ct_ret = NULL;
-       
+       int res;
+
        mono_once (&thread_hash_once, thread_hash_init);
        mono_once (&thread_ops_once, thread_ops_init);
-       
-       if (start == NULL) {
-               return(NULL);
-       }
 
        thread_handle.state = THREAD_STATE_START;
        thread_handle.owned_mutexes = g_ptr_array_new ();
-       thread_handle.create_flags = create;
-       thread_handle.start_routine = start;
-       thread_handle.start_arg = param;
-       
+
        handle = _wapi_handle_new (WAPI_HANDLE_THREAD, &thread_handle);
        if (handle == _WAPI_HANDLE_INVALID) {
                g_warning ("%s: error creating thread handle", __func__);
                SetLastError (ERROR_GEN_FAILURE);
                
-               return (NULL);
+               return NULL;
        }
 
-       pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
-                             handle);
-       thr_ret = _wapi_handle_lock_handle (handle);
-       g_assert (thr_ret == 0);
-       
-       ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
-                                 (gpointer *)&thread_handle_p);
-       if (ok == FALSE) {
-               g_warning ("%s: error looking up thread handle %p", __func__,
-                          handle);
-               SetLastError (ERROR_GEN_FAILURE);
-               
-               goto cleanup;
-       }
+       res = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
+                                                          (gpointer *)&thread);
+       g_assert (res);
 
-       /* Hold a reference while the thread is active, because we use
-        * the handle to store thread exit information
-        */
-       _wapi_handle_ref (handle);
-       
-       /* Set a 2M stack size.  This is the default on Linux, but BSD
-        * needs it.  (The original bug report from Martin Dvorak <md@9ll.cz>
-        * set the size to 2M-4k.  I don't know why it's short by 4k, so
-        * I'm leaving it as 2M until I'm told differently.)
-        */
-       thr_ret = pthread_attr_init(&attr);
-       g_assert (thr_ret == 0);
-       
-       /* defaults of 2Mb for 32bits and 4Mb for 64bits */
-       /* temporarily changed to use 1 MB: this allows more threads
-        * to be used, as well as using less virtual memory and so
-        * more is available for the GC heap.
-        */
-       if (stacksize == 0){
-#if HAVE_VALGRIND_MEMCHECK_H
-               if (RUNNING_ON_VALGRIND) {
-                       stacksize = 1 << 20;
-               } else {
-                       stacksize = (SIZEOF_VOID_P / 4) * 1024 * 1024;
-               }
-#else
-               stacksize = (SIZEOF_VOID_P / 4) * 1024 * 1024;
-#endif
-       }
+       thread->handle = handle;
 
-#ifdef PTHREAD_STACK_MIN
-       if (stacksize < PTHREAD_STACK_MIN)
-               stacksize = PTHREAD_STACK_MIN;
-#endif
-
-#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
-       thr_ret = pthread_attr_setstacksize(&attr, stacksize);
-       g_assert (thr_ret == 0);
-#endif
-
-       MONO_SEM_INIT (&thread_handle_p->suspend_sem, 0);
-       thread_handle_p->handle = handle;
-       
-
-       ret = mono_threads_pthread_create (&thread_handle_p->id, &attr,
-                                                                          thread_start_routine, (void *)thread_handle_p);
-
-       if (ret != 0) {
-               g_warning ("%s: Error creating native thread handle %s (%d)", __func__,
-                          strerror (ret), ret);
-               SetLastError (ERROR_GEN_FAILURE);
+       res = pthread_setspecific (thread_hash_key, handle);
+       if (res)
+               mono_gc_pthread_exit (NULL);
 
-               /* Two, because of the reference we took above */
-               unrefs = 2;
-               
-               goto cleanup;
-       }
-       ct_ret = handle;
-       
-       DEBUG("%s: Started thread handle %p ID %ld", __func__, handle,
-                 thread_handle_p->id);
-       
-       if (tid != NULL) {
-#ifdef PTHREAD_POINTER_ID
-               /* Don't use GPOINTER_TO_UINT here, it can't cope with
-                * sizeof(void *) > sizeof(uint) when a cast to uint
-                * would overflow
-                */
-               *tid = (gsize)(thread_handle_p->id);
-#else
-               *tid = thread_handle_p->id;
-#endif
-       }
+       thread->id = pthread_self ();
 
-cleanup:
-       thr_ret = _wapi_handle_unlock_handle (handle);
-       g_assert (thr_ret == 0);
-       pthread_cleanup_pop (0);
-       
-       /* Must not call _wapi_handle_unref() with the shared handles
-        * already locked
+       /*
+        * Hold a reference while the thread is active, because we use
+        * the handle to store thread exit information
         */
-       for (i = 0; i < unrefs; i++) {
-               _wapi_handle_unref (handle);
-       }
+       _wapi_handle_ref (handle);
+
+       DEBUG ("%s: started thread id %ld", __func__, thread->id);
        
-       return(ct_ret);
+       return handle;
 }
 
 /* The only time this function is called when tid != pthread_self ()
@@ -677,10 +508,6 @@ static gpointer thread_attach(gsize *tid)
         */
        _wapi_handle_ref (handle);
 
-       /* suspend_sem is not used for attached threads, but
-        * thread_exit() might try to destroy it
-        */
-       MONO_SEM_INIT (&thread_handle_p->suspend_sem, 0);
        thread_handle_p->handle = handle;
        thread_handle_p->id = pthread_self ();
 
@@ -749,51 +576,6 @@ gpointer GetCurrentThread(void)
        return(_WAPI_THREAD_CURRENT);
 }
 
-/**
- * ResumeThread:
- * @handle: the thread handle to resume
- *
- * Decrements the suspend count of thread @handle. A thread can only
- * run if its suspend count is zero.
- *
- * Return value: the previous suspend count, or 0xFFFFFFFF on error.
- */
-guint32 ResumeThread(gpointer handle)
-{
-       struct _WapiHandle_thread *thread_handle;
-       gboolean ok;
-       
-       ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
-                                 (gpointer *)&thread_handle);
-       if (ok == FALSE) {
-               g_warning ("%s: error looking up thread handle %p", __func__,
-                          handle);
-               
-               return (0xFFFFFFFF);
-       }
-
-       /* This is still a kludge that only copes with starting a
-        * thread that was suspended on create, so don't bother with
-        * the suspend count crap yet
-        */
-       _wapi_thread_resume (thread_handle);
-       return(0xFFFFFFFF);
-}
-
-/**
- * SuspendThread:
- * @handle: the thread handle to suspend
- *
- * Increments the suspend count of thread @handle. A thread can only
- * run if its suspend count is zero.
- *
- * Return value: the previous suspend count, or 0xFFFFFFFF on error.
- */
-guint32 SuspendThread(gpointer handle)
-{
-       return(0xFFFFFFFF);
-}
-
 /**
  * SleepEx:
  * @ms: The time in milliseconds to suspend for
@@ -915,30 +697,32 @@ gboolean _wapi_thread_dispatch_apc_queue (gpointer handle)
 }
 
 /*
- * In this implementation, APC_CALLBACK is ignored.
- * if HANDLE refers to the current thread, the only effect this function has 
- * that if called from a signal handler, and the thread was waiting when receiving 
+ * wapi_interrupt_self:
+ *
+ * If this function called from a signal handler, and the thread was waiting when receiving
  * the signal, the wait will be broken after the signal handler returns.
- * In this case, this function is async-signal-safe.
+ * This function is async-signal-safe.
  */
-guint32 QueueUserAPC (WapiApcProc apc_callback, gpointer handle, 
-                     gpointer param)
+void
+wapi_thread_interrupt_self (void)
 {
+       HANDLE handle;
        struct _WapiHandle_thread *thread_handle;
        gboolean ok;
        
+       handle = _wapi_thread_handle_from_id (pthread_self ());
+       g_assert (handle);
+
        ok = _wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
                                  (gpointer *)&thread_handle);
        if (ok == FALSE) {
                g_warning ("%s: error looking up thread handle %p", __func__,
                           handle);
-               return (0);
+               return;
        }
 
-       g_assert (thread_handle->id == (pthread_t)GetCurrentThreadId ());
        /* No locking/memory barriers are needed here */
        thread_handle->has_apc = TRUE;
-       return(1);
 }
 
 /*
index 91073a5e704e528a7542cc4b6ba96077948b141d..0b47ca6093d41b8f07364b3d040d2321ab1a8085 100644 (file)
@@ -335,6 +335,7 @@ Makefile.am: Makefile.am.in
 endif
 
 if !HOST_WIN32
+if SUPPORT_BOEHM
 
 test_sgen_qsort_SOURCES = test-sgen-qsort.c
 test_sgen_qsort_CFLAGS = $(SGEN_DEFINES)
@@ -356,4 +357,5 @@ noinst_PROGRAMS = test-sgen-qsort test-gc-memfuncs
 
 TESTS = test-sgen-qsort test-gc-memfuncs
 
+endif SUPPORT_BOEHM
 endif !HOST_WIN32
index f5090c04508675cbe7b7d91966ed9ea823d1446a..11b6fa58c0980e51b90c9faf16a99d1442065f61 100644 (file)
@@ -62,6 +62,7 @@
 #include <mono/utils/mono-error-internals.h>
 #include <mono/utils/atomic.h>
 #include <mono/utils/mono-memory-model.h>
+#include <mono/utils/mono-threads.h>
 #ifdef HOST_WIN32
 #include <direct.h>
 #endif
@@ -1599,6 +1600,8 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
 /*
 This function raises exceptions so it can cause as sorts of nasty stuff if called
 while holding a lock.
+Returns old file name if shadow copy is disabled, new shadow copy file name if successful
+or NULL if source file not found.
 FIXME bubble up the error instead of raising it here
 */
 char *
@@ -1608,6 +1611,7 @@ mono_make_shadow_copy (const char *filename)
        gchar *sibling_source, *sibling_target;
        gint sibling_source_len, sibling_target_len;
        guint16 *orig, *dest;
+       guint32 attrs;
        char *shadow;
        gboolean copy_result;
        MonoException *exc;
@@ -1660,6 +1664,16 @@ mono_make_shadow_copy (const char *filename)
        orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
        dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
        DeleteFile (dest);
+
+       /* Fix for bug #17066 - make sure we can read the file. if not then don't error but rather 
+        * let the assembly fail to load. This ensures you can do Type.GetType("NS.T, NonExistantAssembly)
+        * and not have it runtime error" */
+       attrs = GetFileAttributes (orig);
+       if (attrs == INVALID_FILE_ATTRIBUTES) {
+               g_free (shadow);
+               return (char *)filename;
+       }
+
        copy_result = CopyFile (orig, dest, FALSE);
 
        /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
@@ -1672,6 +1686,11 @@ mono_make_shadow_copy (const char *filename)
 
        if (copy_result == FALSE) {
                g_free (shadow);
+
+               /* Fix for bug #17251 - if file not found try finding assembly by other means (it is not fatal error) */
+               if (GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND)
+                       return NULL; /* file not found, shadow copy failed */
+
                exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
                mono_raise_exception (exc);
        }
@@ -2372,10 +2391,10 @@ void
 mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
 {
        HANDLE thread_handle;
-       gsize tid;
        MonoAppDomainState prev_state;
        MonoMethod *method;
        unload_data *thread_data;
+       MonoNativeThreadId tid;
        MonoDomain *caller_domain = mono_domain_get ();
 
        /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
@@ -2425,20 +2444,10 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
         * First we create a separate thread for unloading, since
         * we might have to abort some threads, including the current one.
         */
-       /*
-        * If we create a non-suspended thread, the runtime will hang.
-        * See:
-        * http://bugzilla.ximian.com/show_bug.cgi?id=27663
-        */ 
-#if 0
-       thread_handle = mono_create_thread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
-#else
-       thread_handle = mono_create_thread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, thread_data, CREATE_SUSPENDED, &tid);
-       if (thread_handle == NULL) {
+       thread_handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)unload_thread_main, thread_data, 0, CREATE_SUSPENDED, &tid);
+       if (thread_handle == NULL)
                return;
-       }
-       ResumeThread (thread_handle);
-#endif
+       mono_thread_info_resume (tid);
 
        /* Wait for the thread */       
        while (!thread_data->done && WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION) {
index b14709aeabc85b89e7e42f4e39c9b2c6a0d01a89..86a83c3a62eef1860fbbb8cde1d8462dbd92ce49 100644 (file)
 #include <netdb.h>
 #include <unistd.h>
 
-
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/metadata.h>
 #include <mono/metadata/class-internals.h>
 #include <mono/metadata/object-internals.h>
 #include <mono/metadata/threads-types.h>
 #include <mono/metadata/gc-internal.h>
+#include <mono/utils/mono-threads.h>
 #include "attach.h"
 
 /*
@@ -473,14 +473,12 @@ transport_send (int fd, guint8 *data, int len)
 static void
 transport_start_receive (void)
 {
-       gsize tid;
-
        transport_connect ();
 
        if (!listen_fd)
                return;
 
-       receiver_thread_handle = mono_create_thread (NULL, 0, receiver_thread, NULL, 0, &tid);
+       receiver_thread_handle = mono_threads_create_thread (receiver_thread, NULL, 0, 0, NULL);
        g_assert (receiver_thread_handle);
 }
 
index d81608d1825fdde4df88c4276c5e2efb118ff7c8..7ba037f0ff62a31713322bf49dc65c7dc1356424 100644 (file)
@@ -65,6 +65,7 @@ mono_gc_base_init (void)
 {
        MonoThreadInfoCallbacks cb;
        const char *env;
+       int dummy;
 
        if (gc_initialized)
                return;
@@ -191,6 +192,8 @@ mono_gc_base_init (void)
        mono_threads_init (&cb, sizeof (MonoThreadInfo));
        mono_mutex_init (&mono_gc_lock);
 
+       mono_thread_info_attach (&dummy);
+
        mono_gc_enable_events ();
        gc_initialized = TRUE;
 }
index b64c1086e039b0594608e7f2d1c64f9dbd82e47b..4660902e68bc857aa710270d701b60752b0bfe13 100644 (file)
@@ -8009,6 +8009,10 @@ mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
                        }
                } else {
                        /*setup_interfaces don't mono_class_init anything*/
+                       /*FIXME this doesn't handle primitive type arrays.
+                       ICollection<sbyte> x byte [] won't work because candidate->interfaces, for byte[], won't have IList<sbyte>.
+                       A possible way to fix this would be to move that to setup_interfaces from setup_interface_offsets.
+                       */
                        mono_class_setup_interfaces (candidate, &error);
                        if (!mono_error_ok (&error)) {
                                mono_error_cleanup (&error);
@@ -8054,7 +8058,34 @@ mono_class_is_assignable_from_slow (MonoClass *target, MonoClass *candidate)
        if (target->delegate && mono_class_has_variant_generic_params (target))
                return mono_class_is_variant_compatible (target, candidate, FALSE);
 
-       /*FIXME properly handle nullables and arrays */
+       if (target->rank) {
+               MonoClass *eclass, *eoclass;
+
+               if (target->rank != candidate->rank)
+                       return FALSE;
+
+               /* vectors vs. one dimensional arrays */
+               if (target->byval_arg.type != candidate->byval_arg.type)
+                       return FALSE;
+
+               eclass = target->cast_class;
+               eoclass = candidate->cast_class;
+
+               /*
+                * a is b does not imply a[] is b[] when a is a valuetype, and
+                * b is a reference type.
+                */
+
+               if (eoclass->valuetype) {
+                       if ((eclass == mono_defaults.enum_class) ||
+                               (eclass == mono_defaults.enum_class->parent) ||
+                               (eclass == mono_defaults.object_class))
+                               return FALSE;
+               }
+
+               return mono_class_is_assignable_from_slow (target->cast_class, candidate->cast_class);
+       }
+       /*FIXME properly handle nullables */
        /*FIXME properly handle (M)VAR */
        return FALSE;
 }
index 71570dad4844e857ba7fddb12cef10642d266205..f833b941bfb360ae6862d1f66646524974e0e4d1 100644 (file)
@@ -83,7 +83,7 @@ static const DateTimeFormatEntry datetime_format_entries [] = {
        {5566, 2404, 280, 274, 44, 55, 3824, 3827, {16743, 16762, 24623, 16803, 24645, 16856, 16881}, {24667, 24677, 24687, 24700, 24710, 24723, 24739}, {16986, 16990, 16997, 17004, 17011, 17018, 17025}, {24749, 24774, 17061, 24805, 24824, 17103, 24831, 24844, 24860, 24885, 24907, 24935, 0}, {24749, 24774, 17061, 24805, 24824, 17103, 24831, 24844, 24860, 24885, 24907, 24935, 0}, {24957, 24970, 17061, 24989, 24824, 17103, 24831, 25005, 25012, 6652, 25034, 25056, 0}, {24957, 24970, 17061, 24989, 24824, 17103, 24831, 25005, 25012, 6652, 25034, 25056, 0}, 0, 0, 2646, 241, {2404,1345,2365,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,1959,1951,0,0,0,0,0,0,0,0},{280,323,1979,1968,0,0,0,0,0}},
        {25072, 1319, 280, 274, 25126, 5699, 0, 0, {25145, 25152, 25163, 25176, 25189, 25200, 25213}, {25224, 25229, 25234, 25239, 25244, 25249, 25254}, {0, 0, 0, 0, 0, 0, 0}, {25259, 25274, 25283, 25290, 25303, 25310, 25321, 25330, 25339, 25346, 25357, 25368, 0}, {25259, 25274, 25283, 25290, 25303, 25310, 25321, 25330, 25339, 25346, 25357, 25368, 0}, {25379, 25386, 25393, 25400, 25407, 25414, 25421, 25428, 25435, 25442, 25449, 25456, 0}, {25379, 25386, 25393, 25400, 25407, 25414, 25421, 25428, 25435, 25442, 25449, 25456, 0}, 0, 0, 2646, 241, {25463,1319,0,0,0,0,0,0,0,0,0,0,0,0},{25472,0,0,0,0,0,0,0},{331,0,0,0,0,0,0,0,0,0,0,0},{323,0,0,0,0,0,0,0,0}},
        {25493, 1475, 280, 274, 25536, 25569, 25593, 25615, {25640, 25668, 25696, 25733, 25764, 25798, 25823}, {25857, 25873, 25889, 25914, 25933, 25955, 25974}, {25996, 26003, 26010, 26017, 26024, 26031, 26035}, {26045, 26079, 26116, 26150, 26184, 26215, 26252, 26289, 26329, 26363, 26397, 26446, 0}, {26045, 26079, 26116, 26150, 26184, 26215, 26252, 26289, 26329, 26363, 26397, 26446, 0}, {26495, 26508, 26521, 26534, 26547, 26560, 26573, 26586, 26599, 26612, 26628, 26644, 0}, {26495, 26508, 26521, 26534, 26547, 26560, 26573, 26586, 26599, 26612, 26628, 26644, 0}, 0, 0, 239, 241, {1475,1827,1836,1856,1319,1845,1867,1874,1881,0,0,0,0,0},{25493,26660,0,0,0,0,0,0},{274,0,0,0,0,0,0,0,0,0,0,0},{280,0,0,0,0,0,0,0,0}},
-       {3777, 14, 280, 274, 2015, 352, 0, 0, {26708, 26717, 26727, 26739, 26752, 26761, 26773}, {26785, 26789, 26794, 26798, 26802, 26806, 26810}, {2131, 2516, 2508, 2508, 14666, 6308, 2131}, {26814, 26821, 26830, 26837, 2826, 26844, 26852, 26863, 26868, 26873, 26880, 26889, 0}, {26814, 26821, 26830, 26837, 2826, 26844, 26897, 26863, 26868, 26873, 26880, 26889, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, 2, 0, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
+       {3777, 14, 280, 274, 2015, 352, 0, 0, {26708, 26717, 26727, 26739, 26752, 26761, 26773}, {26785, 26789, 26794, 26798, 26802, 26806, 26810}, {2131, 2516, 2508, 2508, 14666, 6308, 2131}, {26814, 26821, 26830, 26837, 2826, 26844, 26852, 26863, 26868, 26873, 26880, 26889, 0}, {26814, 26821, 26830, 26837, 2826, 26844, 26897, 26863, 26868, 26873, 26880, 26889, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, 2, 1, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
        {3777, 14, 280, 331, 26942, 352, 26977, 26993, {27009, 27043, 27074, 27105, 27127, 27170, 27198}, {27223, 27230, 27234, 27238, 27245, 27255, 27262}, {0, 0, 0, 0, 0, 0, 0}, {27266, 27279, 27298, 27311, 27324, 27337, 27356, 27375, 27388, 27404, 27417, 27442, 0}, {27266, 27279, 27298, 27311, 27324, 27337, 27356, 27375, 27388, 27404, 27417, 27442, 0}, {27455, 27459, 27463, 27467, 27471, 27475, 27479, 27483, 27487, 27491, 27498, 27505, 0}, {27455, 27459, 27463, 27467, 27471, 27475, 27479, 27483, 27487, 27491, 27498, 27505, 0}, 0, 0, 239, 241, {1319,0,0,0,0,0,0,0,0,0,0,0,0,0},{3777,9999,0,0,0,0,0,0},{27512,0,0,0,0,0,0,0,0,0,0,0},{280,0,0,0,0,0,0,0,0}},
        {5566, 243, 280, 274, 2015, 352, 27520, 27545, {27570, 27595, 27614, 27642, 27661, 27686, 27705}, {27727, 27735, 27740, 27745, 27750, 27758, 27766}, {0, 0, 0, 0, 0, 0, 0}, {27771, 27790, 27806, 27819, 27832, 27854, 27873, 27895, 27911, 27927, 27940, 27956, 0}, {27771, 27790, 27806, 27819, 27832, 27854, 27873, 27895, 27911, 27927, 27940, 27956, 0}, {27972, 27981, 27990, 28002, 28012, 28021, 28033, 28042, 28051, 28060, 28069, 28078, 0}, {27972, 27981, 27990, 28002, 28012, 28021, 28033, 28042, 28051, 28060, 28069, 28078, 0}, 0, 0, 239, 241, {243,1319,0,0,0,0,0,0,0,0,0,0,0,0},{5566,0,0,0,0,0,0,0},{27512,0,0,0,0,0,0,0,0,0,0,0},{280,0,0,0,0,0,0,0,0}},
        {4290, 243, 323, 331, 949, 4096, 964, 969, {28087, 28095, 28100, 28107, 28117, 28123, 28130}, {28138, 28142, 3971, 28146, 28151, 28155, 28159}, {2797, 2516, 2508, 2508, 4189, 4193, 2131}, {28164, 28172, 6327, 28181, 28187, 28192, 28198, 6361, 28204, 28213, 28221, 28230, 0}, {28164, 28172, 6327, 28181, 28187, 28192, 28198, 6361, 28204, 28213, 28221, 28230, 0}, {28239, 2887, 3971, 28243, 2826, 28247, 28252, 18952, 17483, 28256, 2920, 3979, 0}, {28239, 2887, 3971, 28243, 2826, 28247, 28252, 18952, 17483, 28256, 2920, 3979, 0}, 2, 1, 239, 241, {243,14,1330,1338,1345,1354,1319,0,0,0,0,0,0,0},{4290,4319,4346,0,0,0,0,0},{331,274,35,1421,0,0,0,0,0,0,0,0},{323,280,23,1433,0,0,0,0,0}},
@@ -105,7 +105,7 @@ static const DateTimeFormatEntry datetime_format_entries [] = {
        {4834, 243, 280, 274, 2015, 2025, 32651, 32656, {32661, 32669, 32679, 32689, 32698, 32708, 32716}, {32726, 32730, 32735, 32739, 32743, 32747, 32751}, {2131, 2508, 2797, 2508, 2797, 2514, 2131}, {2799, 2806, 2814, 2820, 2826, 2830, 2835, 32755, 32764, 32775, 32784, 32794, 0}, {2799, 2806, 2814, 2820, 2826, 2830, 2835, 32755, 32764, 32775, 32784, 32794, 0}, {2883, 2887, 2891, 2896, 2826, 2900, 2904, 2908, 2912, 2916, 2920, 2924, 0}, {2883, 2887, 2891, 2896, 2826, 2900, 2904, 2908, 2912, 2916, 2920, 2924, 0}, 0, 0, 239, 241, {243,14,1354,1345,1319,0,0,0,0,0,0,0,0,0},{4834,5053,3777,0,0,0,0,0},{274,331,5062,5068,5078,0,0,0,0,0,0,0},{280,323,0,0,0,0,0,0,0}},
        {32804, 2692, 323, 331, 32839, 32855, 32873, 32878, {32883, 32908, 32937, 32962, 32975, 32990, 33007}, {33022, 33027, 33032, 33037, 33042, 33047, 8601}, {33052, 33052, 33055, 8612, 8615, 33052, 8612}, {33058, 33077, 33092, 33114, 33134, 33150, 33166, 33180, 33206, 33230, 33247, 33264, 0}, {33058, 33077, 33092, 33114, 33134, 33150, 33166, 33180, 33206, 33230, 33247, 33264, 0}, {33281, 33290, 33299, 33313, 33327, 33339, 33351, 33361, 33377, 33391, 33398, 33405, 0}, {33281, 33290, 33299, 33313, 33327, 33339, 33351, 33361, 33377, 33391, 33398, 33405, 0}, 0, 1, 756, 241, {33412,33423,2948,3990,33432,0,0,0,0,0,0,0,0,0},{33443,33461,0,0,0,0,0,0},{331,274,0,0,0,0,0,0,0,0,0,0},{323,280,0,0,0,0,0,0,0}},
        {33480, 14193, 323, 331, 2015, 18811, 0, 0, {33500, 33512, 33523, 33535, 33547, 33557, 33569}, {33584, 33589, 33594, 33599, 33604, 33609, 33614}, {0, 0, 0, 0, 0, 0, 0}, {33619, 33628, 33640, 33648, 33653, 33663, 33670, 33679, 33686, 33692, 33701, 33712, 0}, {33619, 33628, 33640, 33648, 33653, 33663, 33670, 33679, 33686, 33692, 33701, 33712, 0}, {33720, 33725, 33730, 33735, 33740, 33745, 33750, 33604, 33755, 33760, 33765, 33770, 0}, {33720, 33725, 33730, 33735, 33740, 33745, 33750, 33604, 33755, 33760, 33765, 33770, 0}, 0, 0, 239, 241, {3808,3983,3990,3999,1888,1319,4010,0,0,0,0,0,0,0},{4020,4040,254,4054,0,0,0,0},{3052,35,331,274,0,0,0,0,0,0,0,0},{3041,23,323,280,0,0,0,0,0}},
-       {5566, 243, 280, 274, 2015, 352, 6087, 6092, {33775, 33788, 33796, 33805, 33815, 33825, 33834}, {33846, 33850, 33854, 33858, 33862, 33866, 33870}, {2797, 2516, 2508, 7493, 12392, 5774, 2131}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, 2, 0, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
+       {5566, 243, 280, 274, 2015, 352, 6087, 6092, {33775, 33788, 33796, 33805, 33815, 33825, 33834}, {33846, 33850, 33854, 33858, 33862, 33866, 33870}, {2797, 2516, 2508, 7493, 12392, 5774, 2131}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, 2, 1, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
        {1, 14, 23, 35, 44, 55, 0, 0, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, 0, 6, 239, 241, {14,243,0,0,0,0,0,0,0,0,0,0,0,0},{1,254,0,0,0,0,0,0},{35,274,0,0,0,0,0,0,0,0,0,0},{23,280,0,0,0,0,0,0,0}},
        {289, 308, 323, 331, 336, 352, 359, 371, {383, 396, 417, 432, 443, 462, 473}, {486, 491, 496, 501, 506, 511, 516}, {521, 524, 527, 530, 533, 524, 530}, {536, 549, 566, 575, 586, 593, 600, 607, 620, 639, 656, 671, 0}, {536, 549, 566, 575, 586, 593, 600, 607, 620, 639, 656, 671, 0}, {688, 694, 566, 704, 586, 593, 600, 712, 720, 730, 738, 748, 0}, {688, 694, 566, 704, 586, 593, 600, 712, 720, 730, 738, 748, 0}, 2, 1, 756, 241, {308,758,774,790,0,0,0,0,0,0,0,0,0,0},{289,807,825,850,0,0,0,0},{874,886,0,0,0,0,0,0,0,0,0,0},{897,912,0,0,0,0,0,0,0}},
        {926, 243, 323, 331, 949, 352, 964, 969, {974, 983, 991, 999, 1008, 1015, 1025}, {1034, 1037, 1040, 1043, 1046, 1049, 1052}, {1055, 1057, 1059, 1061, 1063, 1065, 1067}, {1069, 1075, 1082, 1088, 1094, 1099, 1104, 1111, 1117, 1126, 1134, 1143, 0}, {1152, 1161, 1171, 1180, 1190, 1198, 1206, 1216, 1226, 1238, 1250, 1262, 0}, {1274, 1279, 1082, 1285, 1094, 1099, 1290, 1295, 1299, 1304, 1309, 1314, 0}, {1274, 1279, 1082, 1285, 1094, 1099, 1290, 1295, 1299, 1304, 1309, 1314, 0}, 2, 1, 239, 241, {243,14,1319,1330,1338,1345,1354,0,0,0,0,0,0,0},{1363,1389,1405,0,0,0,0,0},{274,331,1421,0,0,0,0,0,0,0,0,0},{280,323,1433,0,0,0,0,0,0}},
@@ -174,7 +174,7 @@ static const DateTimeFormatEntry datetime_format_entries [] = {
        {24034, 2404, 1968, 1951, 24053, 352, 24061, 24089, {24111, 24130, 24149, 24174, 24193, 24227, 24252}, {24271, 19372, 19382, 19398, 24281, 24306, 19449}, {0, 0, 0, 0, 0, 0, 0}, {24322, 24347, 24378, 24394, 19596, 19603, 19613, 24413, 24429, 24460, 24482, 24504, 0}, {24322, 24347, 24378, 24394, 19596, 19603, 19613, 24413, 24429, 24460, 24482, 24504, 0}, {24529, 24542, 24378, 24394, 19596, 19603, 19613, 24561, 24568, 24584, 24600, 24610, 0}, {24529, 24542, 24378, 24394, 19596, 19603, 19613, 24561, 24568, 24584, 24600, 24610, 0}, 0, 0, 2646, 241, {2404,0,0,0,0,0,0,0,0,0,0,0,0,0},{24034,0,0,0,0,0,0,0},{1951,1959,0,0,0,0,0,0,0,0,0,0},{1968,1979,0,0,0,0,0,0,0}},
        {5566, 2404, 280, 274, 44, 55, 3824, 3827, {16743, 16762, 24623, 16803, 24645, 16856, 16881}, {24667, 24677, 24687, 24700, 24710, 24723, 24739}, {16986, 16990, 16997, 17004, 17011, 17018, 17025}, {24749, 24774, 17061, 24805, 24824, 17103, 24831, 24844, 24860, 24885, 24907, 24935, 0}, {24749, 24774, 17061, 24805, 24824, 17103, 24831, 24844, 24860, 24885, 24907, 24935, 0}, {24957, 24970, 17061, 24989, 24824, 17103, 24831, 25005, 25012, 6652, 25034, 25056, 0}, {24957, 24970, 17061, 24989, 24824, 17103, 24831, 25005, 25012, 6652, 25034, 25056, 0}, 0, 0, 2646, 241, {2404,1345,2365,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,1959,1951,0,0,0,0,0,0,0,0},{280,323,1979,1968,0,0,0,0,0}},
        {25493, 1475, 280, 274, 25536, 25569, 25593, 25615, {25640, 25668, 25696, 25733, 25764, 25798, 25823}, {25857, 25873, 25889, 25914, 25933, 25955, 25974}, {25996, 26003, 26010, 26017, 26024, 26031, 26035}, {26045, 26079, 26116, 26150, 26184, 26215, 26252, 26289, 26329, 26363, 26397, 26446, 0}, {26045, 26079, 26116, 26150, 26184, 26215, 26252, 26289, 26329, 26363, 26397, 26446, 0}, {26495, 26508, 26521, 26534, 26547, 26560, 26573, 26586, 26599, 26612, 26628, 26644, 0}, {26495, 26508, 26521, 26534, 26547, 26560, 26573, 26586, 26599, 26612, 26628, 26644, 0}, 0, 0, 239, 241, {1475,1827,1836,1856,1319,1845,1867,1874,1881,0,0,0,0,0},{25493,26660,0,0,0,0,0,0},{274,0,0,0,0,0,0,0,0,0,0,0},{280,0,0,0,0,0,0,0,0}},
-       {3777, 14, 280, 274, 2015, 352, 0, 0, {26708, 26717, 26727, 26739, 26752, 26761, 26773}, {26785, 26789, 26794, 26798, 26802, 26806, 26810}, {2131, 2516, 2508, 2508, 14666, 6308, 2131}, {26814, 26821, 26830, 26837, 2826, 26844, 26852, 26863, 26868, 26873, 26880, 26889, 0}, {26814, 26821, 26830, 26837, 2826, 26844, 26897, 26863, 26868, 26873, 26880, 26889, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, 2, 0, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
+       {3777, 14, 280, 274, 2015, 352, 0, 0, {26708, 26717, 26727, 26739, 26752, 26761, 26773}, {26785, 26789, 26794, 26798, 26802, 26806, 26810}, {2131, 2516, 2508, 2508, 14666, 6308, 2131}, {26814, 26821, 26830, 26837, 2826, 26844, 26852, 26863, 26868, 26873, 26880, 26889, 0}, {26814, 26821, 26830, 26837, 2826, 26844, 26897, 26863, 26868, 26873, 26880, 26889, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, {26907, 26911, 26794, 26916, 2826, 26920, 26924, 26863, 26868, 26928, 26932, 26937, 0}, 2, 1, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
        {3777, 14, 280, 331, 26942, 352, 26977, 26993, {27009, 27043, 27074, 27105, 27127, 27170, 27198}, {27223, 27230, 27234, 27238, 27245, 27255, 27262}, {0, 0, 0, 0, 0, 0, 0}, {27266, 27279, 27298, 27311, 27324, 27337, 27356, 27375, 27388, 27404, 27417, 27442, 0}, {27266, 27279, 27298, 27311, 27324, 27337, 27356, 27375, 27388, 27404, 27417, 27442, 0}, {27455, 27459, 27463, 27467, 27471, 27475, 27479, 27483, 27487, 27491, 27498, 27505, 0}, {27455, 27459, 27463, 27467, 27471, 27475, 27479, 27483, 27487, 27491, 27498, 27505, 0}, 0, 0, 239, 241, {1319,0,0,0,0,0,0,0,0,0,0,0,0,0},{3777,9999,0,0,0,0,0,0},{27512,0,0,0,0,0,0,0,0,0,0,0},{280,0,0,0,0,0,0,0,0}},
        {5566, 243, 280, 274, 2015, 352, 27520, 27545, {27570, 27595, 27614, 27642, 27661, 27686, 27705}, {27727, 27735, 27740, 27745, 27750, 27758, 27766}, {0, 0, 0, 0, 0, 0, 0}, {27771, 27790, 27806, 27819, 27832, 27854, 27873, 27895, 27911, 27927, 27940, 27956, 0}, {27771, 27790, 27806, 27819, 27832, 27854, 27873, 27895, 27911, 27927, 27940, 27956, 0}, {27972, 27981, 27990, 28002, 28012, 28021, 28033, 28042, 28051, 28060, 28069, 28078, 0}, {27972, 27981, 27990, 28002, 28012, 28021, 28033, 28042, 28051, 28060, 28069, 28078, 0}, 0, 0, 239, 241, {243,1319,0,0,0,0,0,0,0,0,0,0,0,0},{5566,0,0,0,0,0,0,0},{27512,0,0,0,0,0,0,0,0,0,0,0},{280,0,0,0,0,0,0,0,0}},
        {4290, 243, 323, 331, 949, 4096, 964, 969, {28087, 28095, 28100, 28107, 28117, 28123, 28130}, {28138, 28142, 3971, 28146, 28151, 28155, 28159}, {2797, 2516, 2508, 2508, 4189, 4193, 2131}, {28164, 28172, 6327, 28181, 28187, 28192, 28198, 6361, 28204, 28213, 28221, 28230, 0}, {28164, 28172, 6327, 28181, 28187, 28192, 28198, 6361, 28204, 28213, 28221, 28230, 0}, {28239, 2887, 3971, 28243, 2826, 28247, 28252, 18952, 17483, 28256, 2920, 3979, 0}, {28239, 2887, 3971, 28243, 2826, 28247, 28252, 18952, 17483, 28256, 2920, 3979, 0}, 2, 1, 239, 241, {243,14,1330,1338,1345,1354,1319,0,0,0,0,0,0,0},{4290,4319,4346,0,0,0,0,0},{331,274,35,1421,0,0,0,0,0,0,0,0},{323,280,23,1433,0,0,0,0,0}},
@@ -194,11 +194,11 @@ static const DateTimeFormatEntry datetime_format_entries [] = {
        {32502, 243, 6517, 5068, 949, 352, 0, 0, {32524, 32532, 32539, 32547, 32557, 32565, 1025}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {32576, 32584, 1082, 1088, 4966, 32593, 32598, 1111, 1117, 32605, 1134, 32614, 0}, {32576, 32584, 1082, 1088, 4966, 32593, 32598, 1111, 1117, 32605, 1134, 32614, 0}, {6634, 6636, 6638, 6640, 6642, 6644, 6646, 6648, 6650, 6652, 6655, 6658, 0}, {6634, 6636, 6638, 6640, 6642, 6644, 6646, 6648, 6650, 6652, 6655, 6658, 0}, 2, 1, 239, 241, {243,14,1354,1345,1319,0,0,0,0,0,0,0,0,0},{32623,0,0,0,0,0,0,0},{274,331,5062,5068,5078,0,0,0,0,0,0,0},{280,323,0,0,0,0,0,0,0}},
        {32804, 2692, 323, 331, 32839, 32855, 32873, 32878, {32883, 32908, 32937, 32962, 32975, 32990, 33007}, {33022, 33027, 33032, 33037, 33042, 33047, 8601}, {33052, 33052, 33055, 8612, 8615, 33052, 8612}, {33058, 33077, 33092, 33114, 33134, 33150, 33166, 33180, 33206, 33230, 33247, 33264, 0}, {33058, 33077, 33092, 33114, 33134, 33150, 33166, 33180, 33206, 33230, 33247, 33264, 0}, {33281, 33290, 33299, 33313, 33327, 33339, 33351, 33361, 33377, 33391, 33398, 33405, 0}, {33281, 33290, 33299, 33313, 33327, 33339, 33351, 33361, 33377, 33391, 33398, 33405, 0}, 0, 1, 756, 241, {33412,33423,2948,3990,33432,0,0,0,0,0,0,0,0,0},{33443,33461,0,0,0,0,0,0},{331,274,0,0,0,0,0,0,0,0,0,0},{323,280,0,0,0,0,0,0,0}},
        {33480, 14193, 323, 331, 2015, 18811, 0, 0, {33500, 33512, 33523, 33535, 33547, 33557, 33569}, {33584, 33589, 33594, 33599, 33604, 33609, 33614}, {0, 0, 0, 0, 0, 0, 0}, {33619, 33628, 33640, 33648, 33653, 33663, 33670, 33679, 33686, 33692, 33701, 33712, 0}, {33619, 33628, 33640, 33648, 33653, 33663, 33670, 33679, 33686, 33692, 33701, 33712, 0}, {33720, 33725, 33730, 33735, 33740, 33745, 33750, 33604, 33755, 33760, 33765, 33770, 0}, {33720, 33725, 33730, 33735, 33740, 33745, 33750, 33604, 33755, 33760, 33765, 33770, 0}, 0, 0, 239, 241, {3808,3983,3990,3999,1888,1319,4010,0,0,0,0,0,0,0},{4020,4040,254,4054,0,0,0,0},{3052,35,331,274,0,0,0,0,0,0,0,0},{3041,23,323,280,0,0,0,0,0}},
-       {5566, 243, 280, 274, 2015, 352, 6087, 6092, {33775, 33788, 33796, 33805, 33815, 33825, 33834}, {33846, 33850, 33854, 33858, 33862, 33866, 33870}, {2797, 2516, 2508, 7493, 12392, 5774, 2131}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, 2, 0, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
+       {5566, 243, 280, 274, 2015, 352, 6087, 6092, {33775, 33788, 33796, 33805, 33815, 33825, 33834}, {33846, 33850, 33854, 33858, 33862, 33866, 33870}, {2797, 2516, 2508, 7493, 12392, 5774, 2131}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {33874, 33888, 33899, 33908, 33919, 33931, 33945, 33957, 33970, 33983, 33995, 34008, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, {34022, 34027, 34033, 34039, 34044, 34050, 34056, 34061, 34067, 34072, 18215, 34078, 0}, 2, 1, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
        {4054, 243, 23, 35, 44, 55, 0, 0, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, {63, 72, 79, 99, 119, 143, 167, 174, 185, 196, 205, 223, 0}, 0, 6, 239, 241, {243,14,1319,0,0,0,0,0,0,0,0,0,0,0},{4054,254,0,0,0,0,0,0},{35,274,0,0,0,0,0,0,0,0,0,0},{23,280,0,0,0,0,0,0,0}},
        {1453, 1475, 323, 331, 1484, 1500, 1513, 1520, {1527, 1537, 1547, 1557, 1567, 1577, 1587}, {1597, 1604, 1611, 1618, 1625, 1632, 1639}, {1646, 1650, 1654, 1658, 1662, 1666, 1670}, {1674, 1681, 1688, 1695, 1702, 1709, 1716, 1723, 1730, 1737, 1744, 1754, 0}, {1764, 1769, 1774, 1779, 1784, 1789, 1794, 1799, 1804, 1809, 1815, 1821, 0}, {1674, 1681, 1688, 1695, 1702, 1709, 1716, 1723, 1730, 1737, 1744, 1754, 0}, {1674, 1681, 1688, 1695, 1702, 1709, 1716, 1723, 1730, 1737, 1744, 1754, 0}, 0, 0, 239, 241, {1475,1827,1836,1319,1845,1856,1867,1874,1881,1888,0,0,0,0},{1453,1897,1924,0,0,0,0,0},{331,274,1951,1959,0,0,0,0,0,0,0,0},{323,280,1968,1979,0,0,0,0,0}},
        {2673, 2692, 280, 274, 2015, 2025, 2703, 2709, {2716, 2724, 2731, 2740, 2749, 2760, 2768}, {2776, 2779, 2782, 2785, 2788, 2791, 2794}, {2131, 2508, 2797, 2508, 2797, 2514, 2131}, {2799, 2806, 2814, 2820, 2826, 2830, 2835, 2840, 2847, 2857, 2865, 2874, 0}, {2799, 2806, 2814, 2820, 2826, 2830, 2835, 2840, 2847, 2857, 2865, 2874, 0}, {2883, 2887, 2891, 2896, 2826, 2900, 2904, 2908, 2912, 2916, 2920, 2924, 0}, {2883, 2887, 2891, 2896, 2826, 2900, 2904, 2908, 2912, 2916, 2920, 2924, 0}, 2, 1, 756, 241, {2692,1354,2940,34265,2948,1319,0,0,0,0,0,0,0,0},{2673,1991,34275,0,0,0,0,0},{274,331,8154,8144,2967,8177,8182,8163,8169,0,0,0},{280,323,8214,8227,2992,2978,3007,0,0}},
-       {5566, 243, 280, 274, 2015, 352, 3824, 3827, {3830, 3837, 3844, 3852, 3862, 3871, 3878}, {3887, 3891, 3895, 3899, 3903, 3907, 3911}, {2131, 2508, 2510, 3915, 2510, 2514, 2131}, {3917, 3925, 3934, 2820, 3940, 3944, 3949, 2840, 2847, 3954, 2865, 3962, 0}, {3917, 3925, 3934, 2820, 3940, 3944, 3949, 2840, 2847, 3954, 2865, 3962, 0}, {2883, 2887, 3971, 2896, 3940, 2900, 2904, 2908, 2912, 3975, 2920, 3979, 0}, {2883, 2887, 3971, 2896, 3940, 2900, 2904, 2908, 2912, 3975, 2920, 3979, 0}, 2, 0, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
+       {5566, 243, 280, 274, 2015, 352, 3824, 3827, {3830, 3837, 3844, 3852, 3862, 3871, 3878}, {3887, 3891, 3895, 3899, 3903, 3907, 3911}, {2131, 2508, 2510, 3915, 2510, 2514, 2131}, {3917, 3925, 3934, 2820, 3940, 3944, 3949, 2840, 2847, 3954, 2865, 3962, 0}, {3917, 3925, 3934, 2820, 3940, 3944, 3949, 2840, 2847, 3954, 2865, 3962, 0}, {2883, 2887, 3971, 2896, 3940, 2900, 2904, 2908, 2912, 3975, 2920, 3979, 0}, {2883, 2887, 3971, 2896, 3940, 2900, 2904, 2908, 2912, 3975, 2920, 3979, 0}, 2, 1, 239, 241, {243,14,1338,2948,1319,0,0,0,0,0,0,0,0,0},{5566,3777,0,0,0,0,0,0},{274,331,35,3052,0,0,0,0,0,0,0,0},{280,323,23,3041,0,0,0,0,0}},
        {4068, 243, 23, 35, 949, 4096, 964, 969, {4108, 4116, 4122, 4129, 4140, 4147, 4155}, {4163, 4167, 2610, 4171, 4176, 4180, 4184}, {2797, 2516, 2508, 2508, 4191, 4193, 2131}, {4195, 4201, 4209, 1088, 4215, 4220, 4226, 4232, 4239, 1126, 4250, 4260, 0}, {4195, 4201, 4209, 1088, 4215, 4220, 4226, 4232, 4239, 1126, 4250, 4260, 0}, {4270, 2606, 2610, 4274, 4215, 2618, 2622, 4278, 2630, 4282, 2638, 4286, 0}, {4270, 2606, 2610, 4274, 4215, 2618, 2622, 4278, 2630, 4282, 2638, 4286, 0}, 0, 0, 239, 241, {243,3765,14,1330,1338,1345,1319,0,0,0,0,0,0,0},{4290,4319,4346,0,0,0,0,0},{35,3052,331,274,0,0,0,0,0,0,0,0},{23,3041,323,280,0,0,0,0,0}},
        {4834, 1345, 280, 274, 2015, 352, 3824, 3827, {4851, 4860, 4866, 4872, 4881, 4887, 4896}, {4903, 4908, 4913, 4918, 4923, 4928, 4933}, {2797, 2516, 2508, 2508, 4191, 4193, 2131}, {4938, 4946, 4955, 4960, 4966, 4970, 4975, 4983, 4989, 4999, 1134, 5007, 0}, {4938, 4946, 4955, 4960, 4966, 4970, 4975, 4983, 4989, 4999, 1134, 5007, 0}, {5017, 5023, 4955, 5030, 4966, 4970, 5035, 4983, 5041, 1304, 1309, 5047, 0}, {5017, 5023, 4955, 5030, 4966, 4970, 5035, 4983, 5041, 1304, 1309, 5047, 0}, 2, 1, 2646, 241, {14193,1330,1354,1888,1345,243,1319,0,0,0,0,0,0,0},{4834,3777,4010,0,0,0,0,0},{274,331,5062,5068,5078,0,0,0,0,0,0,0},{280,323,0,0,0,0,0,0,0}},
        {2673, 2692, 280, 274, 2015, 352, 6224, 6227, {6230, 6239, 6247, 6256, 6267, 6276, 6285}, {4163, 4167, 2610, 6292, 6296, 6300, 6304}, {2797, 2516, 2508, 2508, 6308, 4193, 2131}, {6310, 6318, 6327, 6333, 6340, 6347, 6354, 6361, 6368, 6378, 6386, 6395, 0}, {6404, 6412, 4209, 6421, 6428, 6435, 6442, 4232, 6449, 6459, 1134, 6467, 0}, {6476, 2606, 2610, 2614, 6480, 6484, 6488, 4278, 6492, 6496, 2638, 4286, 0}, {6476, 2606, 2610, 2614, 6480, 6484, 6488, 4278, 6492, 6496, 2638, 4286, 0}, 2, 1, 756, 241, {2692,1354,11704,1338,6500,1319,0,0,0,0,0,0,0,0},{2673,6508,3777,0,0,0,0,0},{274,331,8154,0,0,0,0,0,0,0,0,0},{280,323,0,0,0,0,0,0,0}},
index f38a054125710fab5281f9e0facb68b7aa1e5e4f..a20e8ae06e03a9ade8d5e64419f4d0a4b9122220 100644 (file)
@@ -468,6 +468,8 @@ match_class (MonoMethodDesc *desc, int pos, MonoClass *klass)
 gboolean
 mono_method_desc_full_match (MonoMethodDesc *desc, MonoMethod *method)
 {
+       if (!desc->klass)
+               return FALSE;
        if (!match_class (desc, strlen (desc->klass), method->klass))
                return FALSE;
 
index aca4ec8549b5e57dd5a3e3dcda958f0daec1c850..5c559247a917db1aec2ce081b02a7f6a3964ec47 100644 (file)
@@ -25,6 +25,7 @@
 #include <mono/utils/hazard-pointer.h>
 #include <mono/utils/mono-tls.h>
 #include <mono/utils/mono-mmap.h>
+#include <mono/utils/mono-threads.h>
 #include <mono/metadata/object.h>
 #include <mono/metadata/object-internals.h>
 #include <mono/metadata/domain-internals.h>
@@ -58,17 +59,25 @@ MONO_FAST_TLS_DECLARE(tls_appdomain);
 #define GET_APPDOMAIN() ((MonoDomain*)MONO_FAST_TLS_GET(tls_appdomain))
 
 #define SET_APPDOMAIN(x) do { \
+       MonoThreadInfo *info; \
        MONO_FAST_TLS_SET (tls_appdomain,x); \
        mono_native_tls_set_value (appdomain_thread_id, x); \
        mono_gc_set_current_thread_appdomain (x); \
+       info = mono_thread_info_current (); \
+       if (info) \
+               mono_thread_info_tls_set (info, TLS_KEY_DOMAIN, (x));   \
 } while (FALSE)
 
 #else /* !MONO_HAVE_FAST_TLS */
 
 #define GET_APPDOMAIN() ((MonoDomain *)mono_native_tls_get_value (appdomain_thread_id))
 #define SET_APPDOMAIN(x) do {                                          \
+               MonoThreadInfo *info;                                                           \
                mono_native_tls_set_value (appdomain_thread_id, x);     \
                mono_gc_set_current_thread_appdomain (x);               \
+               info = mono_thread_info_current ();                             \
+               if (info)                                                                                                \
+                       mono_thread_info_tls_set (info, TLS_KEY_DOMAIN, (x));   \
        } while (FALSE)
 
 #endif
index 64a70d73f8f421f2584711ce90e3ba8ae9639821..4b2c5d9355757465d2d546bad700818caf36166f 100644 (file)
@@ -86,6 +86,7 @@
 #include <mono/utils/mono-digest.h>
 #include <mono/utils/bsearch.h>
 #include <mono/utils/mono-mutex.h>
+#include <mono/utils/mono-threads.h>
 
 #if defined (HOST_WIN32)
 #include <windows.h>
@@ -927,7 +928,7 @@ ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStac
        size_t stack_size;
        /* later make this configurable and per-arch */
        int min_size = 4096 * 4 * sizeof (void*);
-       mono_thread_get_stack_bounds (&stack_addr, &stack_size);
+       mono_thread_info_get_stack_bounds (&stack_addr, &stack_size);
        /* if we have no info we are optimistic and assume there is enough room */
        if (!stack_addr)
                return TRUE;
@@ -1559,9 +1560,6 @@ ves_icall_type_is_assignable_from (MonoReflectionType *type, MonoReflectionType
        klass = mono_class_from_mono_type (type->type);
        klassc = mono_class_from_mono_type (c->type);
 
-       mono_class_init_or_throw (klass);
-       mono_class_init_or_throw (klassc);
-
        if (type->type->byref ^ c->type->byref)
                return FALSE;
 
index 18941dc4a2a4acb1e1c657cdb21913b6e84534c3..f950055953eaa5f728b435c793012fb8ac6f895d 100644 (file)
@@ -532,13 +532,13 @@ mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
                return result;
        }
 
-       mono_loader_lock ();
+       mono_image_lock (image);
        if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
                *retklass = field->parent;
-               mono_loader_unlock ();
+               mono_image_unlock (image);
                return field;
        }
-       mono_loader_unlock ();
+       mono_image_unlock (image);
 
        if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
                field = field_from_memberref (image, token, retklass, context);
@@ -555,10 +555,10 @@ mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
                field = mono_class_get_field (k, token);
        }
 
-       mono_loader_lock ();
+       mono_image_lock (image);
        if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container)
                g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
-       mono_loader_unlock ();
+       mono_image_unlock (image);
        return field;
 }
 
index fa50598f7d72c68a36f2b4396988c2f24a6b61ba..9aa3badf700549cec88283e8257d9b08ac26a258 100644 (file)
@@ -12290,7 +12290,7 @@ mono_marshal_load_type_info (MonoClass* klass)
                case TYPE_ATTRIBUTE_EXPLICIT_LAYOUT:
                        size = mono_marshal_type_size (field->type, info->fields [j].mspec, 
                                                       &align, TRUE, klass->unicode);
-                       min_align = packing;
+                       min_align = MAX (align, min_align);
                        info->fields [j].offset = field->offset - sizeof (MonoObject);
                        info->native_size = MAX (info->native_size, info->fields [j].offset + size);
                        break;
@@ -12304,9 +12304,12 @@ mono_marshal_load_type_info (MonoClass* klass)
                 * If the provided Size is equal or larger than the calculated size, and there
                 * was no Pack attribute, we set min_align to 1 to avoid native_size being increased
                 */
-               if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
+               if (layout == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
                        if (native_size && native_size == info->native_size && klass->packing_size == 0)
                                min_align = 1;
+                       else
+                               min_align = MIN (min_align, packing);
+               }
        }
 
        if (info->native_size & (min_align - 1)) {
index 53ff05e493c2c2c8956a0e5d42c49f7b00f94e4f..ed403c65dc17f77ed2a4267e6b6defdaea55d9c5 100644 (file)
@@ -224,7 +224,7 @@ struct _MonoImage {
        /*
         * Indexed by fielddef and memberref tokens
         */
-       GHashTable *field_cache;
+       GHashTable *field_cache; /*protected by the image lock*/
 
        /* indexed by typespec tokens. */
        GHashTable *typespec_cache;
index 45edc7be4ab6081197b55b0e88c2e7907e0ea9bb..23cca50895138efb1ab1964ff0103da85f4ae5e8 100644 (file)
@@ -4083,6 +4083,9 @@ ptr_on_stack (void *ptr)
 static void*
 sgen_thread_register (SgenThreadInfo* info, void *addr)
 {
+       size_t stsize = 0;
+       guint8 *staddr = NULL;
+
 #ifndef HAVE_KW_THREAD
        info->tlab_start = info->tlab_next = info->tlab_temp_end = info->tlab_real_end = NULL;
 
@@ -4110,48 +4113,16 @@ sgen_thread_register (SgenThreadInfo* info, void *addr)
 
        binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
 
-       // FIXME: Unift with mono_thread_get_stack_bounds ()
-       /* try to get it with attributes first */
-#if (defined(HAVE_PTHREAD_GETATTR_NP) || defined(HAVE_PTHREAD_ATTR_GET_NP)) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
-  {
-     size_t size;
-     void *sstart;
-     pthread_attr_t attr;
-
-#if defined(HAVE_PTHREAD_GETATTR_NP)
-    /* Linux */
-    pthread_getattr_np (pthread_self (), &attr);
-#elif defined(HAVE_PTHREAD_ATTR_GET_NP)
-    /* BSD */
-    pthread_attr_init (&attr);
-    pthread_attr_get_np (pthread_self (), &attr);
-#else
-#error Cannot determine which API is needed to retrieve pthread attributes.
-#endif
-
-     pthread_attr_getstack (&attr, &sstart, &size);
-     info->stack_start_limit = sstart;
-     info->stack_end = (char*)sstart + size;
-     pthread_attr_destroy (&attr);
-  }
-#elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
-       {
-               size_t stsize = 0;
-               guint8 *staddr = NULL;
-
-               mono_thread_get_stack_bounds (&staddr, &stsize);
+       mono_thread_info_get_stack_bounds (&staddr, &stsize);
+       if (staddr) {
                info->stack_start_limit = staddr;
                info->stack_end = staddr + stsize;
-       }
-#else
-       {
-               /* FIXME: we assume the stack grows down */
+       } else {
                gsize stack_bottom = (gsize)addr;
                stack_bottom += 4095;
                stack_bottom &= ~4095;
                info->stack_end = (char*)stack_bottom;
        }
-#endif
 
 #ifdef HAVE_KW_THREAD
        stack_end = info->stack_end;
index 2a902bdd4f06096197366f98bb421d5348f288a8..c7c1a9b6fb13494952e7ff944c495c7e7f337187 100644 (file)
@@ -70,8 +70,7 @@ sgen_suspend_thread (SgenThreadInfo *info)
        mono_mach_arch_thread_state_to_mcontext (state, mctx);
        ctx.uc_mcontext = mctx;
 
-       info->stopped_domain = mono_mach_arch_get_tls_value_from_thread (
-               mono_thread_info_get_tid (info), mono_domain_get_tls_key ());
+       info->stopped_domain = mono_thread_info_tls_get (info, TLS_KEY_DOMAIN);
        info->stopped_ip = (gpointer) mono_mach_arch_get_ip (state);
        info->stack_start = NULL;
        stack_start = (char*) mono_mach_arch_get_sp (state) - REDZONE_SIZE;
index 4b57884b0ff8d19640b3a5cd3939fe53c2b0e42d..1290e0444a92a3d3aec1197052aa20df0d6220c4 100644 (file)
@@ -69,8 +69,13 @@ qsort_rec (void *base, size_t nel, size_t width, int (*compar) (const void*, con
 void
 sgen_qsort (void *base, size_t nel, size_t width, int (*compar) (const void*, const void*))
 {
+#ifndef _MSC_VER
        unsigned char pivot_tmp [width];
        unsigned char swap_tmp [width];
+#else
+       unsigned char* pivot_tmp = (unsigned char*) alloca(width);
+       unsigned char* swap_tmp = (unsigned char*) alloca(width);
+#endif
 
        qsort_rec (base, nel, width, compar, pivot_tmp, swap_tmp);
 }
index 54dc218b5848891e22c00f495f5b6de8a3093926..12111cbc32dd66949192143a28b0c9935f37abbb 100755 (executable)
@@ -147,11 +147,7 @@ restart_threads_until_none_in_managed_allocator (void)
                sgen_wait_for_suspend_ack (restart_count);
 
                if (sleep_duration < 0) {
-#ifdef HOST_WIN32
-                       SwitchToThread ();
-#else
-                       sched_yield ();
-#endif
+                       mono_thread_info_yield ();
                        sleep_duration = 0;
                } else {
                        g_usleep (sleep_duration);
index 8710dafd661e8d26ac41f99ec451bd617400a474..6d0996e444ae93f529fcb6ec567e7c5cf8eb9a94 100644 (file)
@@ -1300,9 +1300,10 @@ try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
 static gboolean
 dequeue_or_steal (ThreadPool *tp, gpointer *data, MonoWSQ *local_wsq)
 {
-       if (mono_runtime_is_shutting_down ())
+       MonoCQ *queue = tp->queue;
+       if (mono_runtime_is_shutting_down () || !queue)
                return FALSE;
-       mono_cq_dequeue (tp->queue, (MonoObject **) data);
+       mono_cq_dequeue (queue, (MonoObject **) data);
        if (!tp->is_io && !*data)
                try_steal (local_wsq, data, FALSE);
        return (*data != NULL);
index cf567afba74d7bc7f1e64141f60d56584cbe48d6..9bb31a87095fa0f01929097e6d3d28340395d77b 100644 (file)
@@ -54,10 +54,6 @@ typedef struct _MonoInternalThread MonoInternalThread;
 
 typedef void (*MonoThreadCleanupFunc) (MonoInternalThread* thread);
 
-gpointer mono_create_thread (WapiSecurityAttributes *security,
-                                                        guint32 stacksize, WapiThreadStart start,
-                                                        gpointer param, guint32 create, gsize *tid) MONO_INTERNAL;
-
 MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, gboolean no_detach, guint32 stack_size) MONO_INTERNAL;
 
 void mono_threads_install_cleanup (MonoThreadCleanupFunc func) MONO_INTERNAL;
@@ -190,7 +186,6 @@ void     mono_thread_destroy_tls (uint32_t tls_offset) MONO_INTERNAL;
 void     mono_thread_destroy_domain_tls (MonoDomain *domain) MONO_INTERNAL;
 void mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local) MONO_INTERNAL;
 void mono_thread_current_check_pending_interrupt (void) MONO_INTERNAL;
-void mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize) MONO_INTERNAL;
 
 void mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state) MONO_INTERNAL;
 void mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state) MONO_INTERNAL;
index cb247800e39889d51401bed6322e68a91f1bb22e..fc89ad076e58ca59a4f36b10e254927b4ab3de5d 100755 (executable)
 #include <signal.h>
 #include <string.h>
 
-#if defined(__OpenBSD__) || defined(__FreeBSD__)
-#include <pthread.h>
-#include <pthread_np.h>
-#endif
-
 #include <mono/metadata/object.h>
 #include <mono/metadata/domain-internals.h>
 #include <mono/metadata/profiler-private.h>
 extern int tkill (pid_t tid, int signal);
 #endif
 
-#if defined(PLATFORM_MACOSX) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
-void *pthread_get_stackaddr_np(pthread_t);
-size_t pthread_get_stacksize_np(pthread_t);
-#endif
-
 /*#define THREAD_DEBUG(a) do { a; } while (0)*/
 #define THREAD_DEBUG(a)
 /*#define THREAD_WAIT_DEBUG(a) do { a; } while (0)*/
@@ -78,6 +68,9 @@ size_t pthread_get_stacksize_np(pthread_t);
 
 #define SPIN_UNLOCK(i) i = 0
 
+#define LOCK_THREAD(thread) lock_thread((thread))
+#define UNLOCK_THREAD(thread) unlock_thread((thread))
+
 /* Provide this for systems with glib < 2.6 */
 #ifndef G_GSIZE_FORMAT
 #   if GLIB_SIZEOF_LONG == 8
@@ -87,13 +80,13 @@ size_t pthread_get_stacksize_np(pthread_t);
 #   endif
 #endif
 
-struct StartInfo 
+typedef struct
 {
        guint32 (*func)(void *);
        MonoThread *obj;
        MonoObject *delegate;
        void *start_arg;
-};
+} StartInfo;
 
 typedef union {
        gint32 ival;
@@ -195,7 +188,6 @@ static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
 static void mono_init_static_data_info (StaticDataInfo *static_data);
 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
 static gboolean mono_thread_resume (MonoInternalThread* thread);
-static void mono_thread_start (MonoThread *thread);
 static void signal_thread_state_change (MonoInternalThread *thread);
 static void abort_thread_internal (MonoInternalThread *thread, gboolean can_raise_exception, gboolean install_async_abort);
 static void suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt);
@@ -321,23 +313,17 @@ static gboolean handle_remove(MonoInternalThread *thread)
        return ret;
 }
 
-static void ensure_synch_cs_set (MonoInternalThread *thread)
+static inline void
+lock_thread (MonoInternalThread *thread)
 {
-       CRITICAL_SECTION *synch_cs;
-       
-       if (thread->synch_cs != NULL) {
-               return;
-       }
-       
-       synch_cs = g_new0 (CRITICAL_SECTION, 1);
-       InitializeCriticalSection (synch_cs);
-       
-       if (InterlockedCompareExchangePointer ((gpointer *)&thread->synch_cs,
-                                              synch_cs, NULL) != NULL) {
-               /* Another thread must have installed this CS */
-               DeleteCriticalSection (synch_cs);
-               g_free (synch_cs);
-       }
+       g_assert (thread->synch_cs);
+       EnterCriticalSection (thread->synch_cs);
+}
+
+static inline void
+unlock_thread (MonoInternalThread *thread)
+{
+       LeaveCriticalSection (thread->synch_cs);
 }
 
 /*
@@ -367,14 +353,16 @@ static void thread_cleanup (MonoInternalThread *thread)
                        mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
        }
 
-       ensure_synch_cs_set (thread);
-
-       EnterCriticalSection (thread->synch_cs);
+       if (thread->synch_cs)
+               LOCK_THREAD (thread);
+       else
+               g_assert (shutting_down);
 
        thread->state |= ThreadState_Stopped;
        thread->state &= ~ThreadState_Background;
 
-       LeaveCriticalSection (thread->synch_cs);
+       if (thread->synch_cs)
+               UNLOCK_THREAD (thread);
 
        /*
        An interruption request has leaked to cleanup. Adjust the global counter.
@@ -430,7 +418,6 @@ static void thread_cleanup (MonoInternalThread *thread)
                MONO_GC_UNREGISTER_ROOT (thread->thread_pinning_ref);
                thread->thread_pinning_ref = NULL;
        }
-               
 }
 
 static gpointer
@@ -475,13 +462,6 @@ set_current_thread_for_domain (MonoDomain *domain, MonoInternalThread *thread, M
        *current_thread_ptr = current;
 }
 
-static MonoInternalThread*
-create_internal_thread_object (void)
-{
-       MonoVTable *vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
-       return (MonoInternalThread*)mono_gc_alloc_mature (vt);
-}
-
 static MonoThread*
 create_thread_object (MonoDomain *domain)
 {
@@ -497,6 +477,28 @@ new_thread_with_internal (MonoDomain *domain, MonoInternalThread *internal)
        return thread;
 }
 
+static MonoInternalThread*
+create_internal_thread (void)
+{
+       MonoInternalThread *thread;
+       MonoVTable *vt;
+
+       vt = mono_class_vtable (mono_get_root_domain (), mono_defaults.internal_thread_class);
+       thread = (MonoInternalThread*)mono_gc_alloc_mature (vt);
+
+       thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
+       InitializeCriticalSection (thread->synch_cs);
+
+       thread->apartment_state = ThreadApartmentState_Unknown;
+       thread->managed_id = get_next_managed_thread_id ();
+       if (mono_gc_is_moving ()) {
+               thread->thread_pinning_ref = thread;
+               MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref);
+       }
+
+       return thread;
+}
+
 static void
 init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
 {
@@ -512,7 +514,7 @@ init_root_domain_thread (MonoInternalThread *thread, MonoThread *candidate)
 static guint32 WINAPI start_wrapper_internal(void *data)
 {
        MonoThreadInfo *info;
-       struct StartInfo *start_info=(struct StartInfo *)data;
+       StartInfo *start_info = (StartInfo *)data;
        guint32 (*start_func)(void *);
        void *start_arg;
        gsize tid;
@@ -654,106 +656,53 @@ static guint32 WINAPI start_wrapper(void *data)
        return start_wrapper_internal (data);
 }
 
-void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
-{
-       if (mono_thread_start_cb) {
-               mono_thread_start_cb (tid, stack_start, func);
-       }
-}
-
-void mono_threads_set_default_stacksize (guint32 stacksize)
-{
-       default_stacksize = stacksize;
-}
-
-guint32 mono_threads_get_default_stacksize (void)
-{
-       return default_stacksize;
-}
-
 /*
- * mono_create_thread:
+ * create_thread:
  *
- *   This is a wrapper around CreateThread which handles differences in the type of
- * the the 'tid' argument.
- */
-gpointer mono_create_thread (WapiSecurityAttributes *security,
-                                                        guint32 stacksize, WapiThreadStart start,
-                                                        gpointer param, guint32 create, gsize *tid)
-{
-       gpointer res;
-
-#ifdef HOST_WIN32
-       DWORD real_tid;
-
-       res = mono_threads_CreateThread (security, stacksize, start, param, create, &real_tid);
-       if (tid)
-               *tid = real_tid;
-#else
-       res = CreateThread (security, stacksize, start, param, create, tid);
-#endif
-
-       return res;
-}
-
-/* 
- * The thread start argument may be an object reference, and there is
- * no ref to keep it alive when the new thread is started but not yet
- * registered with the collector. So we store it in a GC tracked hash
- * table.
- *
- * LOCKING: Assumes the threads lock is held.
- */
-static void
-register_thread_start_argument (MonoThread *thread, struct StartInfo *start_info)
-{
-       if (thread_start_args == NULL) {
-               MONO_GC_REGISTER_ROOT_FIXED (thread_start_args);
-               thread_start_args = mono_g_hash_table_new (NULL, NULL);
-       }
-       mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
-}
-
-/*
- * mono_thread_create_internal:
- * 
- * If NO_DETACH is TRUE, then the thread is not detached using pthread_detach (). This is needed to fix the race condition where waiting for a thred to exit only waits for its exit event to be
- * signalled, which can cause shutdown crashes if the thread shutdown code accesses data already freed by the runtime shutdown.
- * Currently, this is only used for the finalizer thread.
+ *   Common thread creation code.
+ * LOCKING: Acquires the threads lock.
  */
-MonoInternalThread*
-mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, gboolean no_detach, guint32 stack_size)
+static gboolean
+create_thread (MonoThread *thread, MonoInternalThread *internal, StartInfo *start_info, gboolean threadpool_thread, gboolean no_detach, guint32 stack_size,
+                          gboolean throw_on_failure)
 {
-       MonoThread *thread;
-       MonoInternalThread *internal;
        HANDLE thread_handle;
-       struct StartInfo *start_info;
-       gsize tid;
+       MonoNativeThreadId tid;
        guint32 create_flags;
 
-       thread = create_thread_object (domain);
-       internal = create_internal_thread_object ();
-       MONO_OBJECT_SETREF (thread, internal_thread, internal);
-
-       start_info=g_new0 (struct StartInfo, 1);
-       start_info->func = func;
-       start_info->obj = thread;
-       start_info->start_arg = arg;
-
        mono_threads_lock ();
        if (shutting_down) {
-               mono_threads_unlock ();
                g_free (start_info);
-               return NULL;
+               mono_threads_unlock ();
+               return FALSE;
+       }
+       /*
+        * The thread start argument may be an object reference, and there is
+        * no ref to keep it alive when the new thread is started but not yet
+        * registered with the collector. So we store it in a GC tracked hash
+        * table.
+        */
+       if (thread_start_args == NULL) {
+               MONO_GC_REGISTER_ROOT_FIXED (thread_start_args);
+               thread_start_args = mono_g_hash_table_new (NULL, NULL);
        }
+       mono_g_hash_table_insert (thread_start_args, thread, start_info->start_arg);
        if (threads_starting_up == NULL) {
                MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
                threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
        }
+       mono_g_hash_table_insert (threads_starting_up, thread, thread);
+       mono_threads_unlock ();
 
-       register_thread_start_argument (thread, start_info);
-       mono_g_hash_table_insert (threads_starting_up, thread, thread);
-       mono_threads_unlock (); 
+       internal->start_notify = CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
+       if (!internal->start_notify) {
+               mono_threads_lock ();
+               mono_g_hash_table_remove (threads_starting_up, thread);
+               mono_threads_unlock ();
+               g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
+               g_free (start_info);
+               return FALSE;
+       }
 
        if (stack_size == 0)
                stack_size = default_stacksize_for_thread (internal);
@@ -766,187 +715,115 @@ mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gb
        if (no_detach)
                create_flags |= CREATE_NO_DETACH;
 #endif
-       thread_handle = mono_create_thread (NULL, stack_size, (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
-                                    create_flags, &tid);
-       THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
+       thread_handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)start_wrapper, start_info,
+                                                                                               stack_size, create_flags, &tid);
        if (thread_handle == NULL) {
                /* The thread couldn't be created, so throw an exception */
                mono_threads_lock ();
                mono_g_hash_table_remove (threads_starting_up, thread);
                mono_threads_unlock ();
                g_free (start_info);
-               mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
-               return NULL;
-       }
-
-       internal->handle=thread_handle;
-       internal->tid=tid;
-       internal->apartment_state=ThreadApartmentState_Unknown;
-       internal->managed_id = get_next_managed_thread_id ();
-       if (mono_gc_is_moving ()) {
-               internal->thread_pinning_ref = internal;
-               MONO_GC_REGISTER_ROOT_PINNING (internal->thread_pinning_ref);
+               if (throw_on_failure)
+                       mono_raise_exception (mono_get_exception_execution_engine ("Couldn't create thread"));
+               else
+                       g_warning ("%s: CreateThread error 0x%x", __func__, GetLastError ());
+               return FALSE;
        }
+       THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
 
-       internal->synch_cs = g_new0 (CRITICAL_SECTION, 1);
-       InitializeCriticalSection (internal->synch_cs);
+       internal->handle = thread_handle;
+       internal->tid = MONO_NATIVE_THREAD_ID_TO_UINT (tid);
 
        internal->threadpool_thread = threadpool_thread;
        if (threadpool_thread)
                mono_thread_set_state (internal, ThreadState_Background);
 
-       if (handle_store (thread, FALSE))
-               ResumeThread (thread_handle);
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
 
-       /* Check that the managed and unmanaged layout of MonoInternalThread matches */
-       if (mono_check_corlib_version () == NULL)
-               g_assert (((char*)&internal->unused2 - (char*)internal) == mono_defaults.internal_thread_class->fields [mono_defaults.internal_thread_class->field.count - 1].offset);
+       /* Only store the handle when the thread is about to be
+        * launched, to avoid the main thread deadlocking while trying
+        * to clean up a thread that will never be signalled.
+        */
+       if (!handle_store (thread, FALSE))
+               return FALSE;
 
-       return internal;
+       mono_thread_info_resume (tid);
+
+       if (internal->start_notify) {
+               /*
+                * Wait for the thread to set up its TLS data etc, so
+                * theres no potential race condition if someone tries
+                * to look up the data believing the thread has
+                * started
+                */
+               THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
+
+               WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
+               CloseHandle (internal->start_notify);
+               internal->start_notify = NULL;
+       }
+
+       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
+
+       return TRUE;
 }
 
-void
-mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
+void mono_thread_new_init (intptr_t tid, gpointer stack_start, gpointer func)
 {
-       mono_thread_create_internal (domain, func, arg, FALSE, FALSE, 0);
+       if (mono_thread_start_cb) {
+               mono_thread_start_cb (tid, stack_start, func);
+       }
 }
 
-#if defined(HOST_WIN32) && HAVE_DECL___READFSDWORD==0
-static __inline__ __attribute__((always_inline))
-unsigned long long
-__readfsdword (unsigned long offset)
+void mono_threads_set_default_stacksize (guint32 stacksize)
 {
-       unsigned long value;
-       //      __asm__("movl %%fs:%a[offset], %k[value]" : [value] "=q" (value) : [offset] "irm" (offset));
-   __asm__ volatile ("movl    %%fs:%1,%0"
-     : "=r" (value) ,"=m" ((*(volatile long *) offset)));
-       return value;
+       default_stacksize = stacksize;
+}
+
+guint32 mono_threads_get_default_stacksize (void)
+{
+       return default_stacksize;
 }
-#endif
 
 /*
- * mono_thread_get_stack_bounds:
- *
- *   Return the address and size of the current threads stack. Return NULL as the 
- * stack address if the stack address cannot be determined.
+ * mono_thread_create_internal:
+ * 
+ * If NO_DETACH is TRUE, then the thread is not detached using pthread_detach (). This is needed to fix the race condition where waiting for a thred to exit only waits for its exit event to be
+ * signalled, which can cause shutdown crashes if the thread shutdown code accesses data already freed by the runtime shutdown.
+ * Currently, this is only used for the finalizer thread.
  */
-void
-mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
+MonoInternalThread*
+mono_thread_create_internal (MonoDomain *domain, gpointer func, gpointer arg, gboolean threadpool_thread, gboolean no_detach, guint32 stack_size)
 {
-#if defined(HOST_WIN32)
-       /* Windows */
-       /* http://en.wikipedia.org/wiki/Win32_Thread_Information_Block */
-       void* tib = (void*)__readfsdword(0x18);
-       guint8 *stackTop = (guint8*)*(int*)((char*)tib + 4);
-       guint8 *stackBottom = (guint8*)*(int*)((char*)tib + 8);
-
-       *staddr = stackBottom;
-       *stsize = stackTop - stackBottom;
-       return;
-
-#elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
-       /* Mac OS X */
-       *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self());
-       *stsize = pthread_get_stacksize_np (pthread_self());
-
-
-#ifdef TARGET_OSX
-       /*
-        * Mavericks reports stack sizes as 512kb:
-        * http://permalink.gmane.org/gmane.comp.java.openjdk.hotspot.devel/11590
-        * https://bugs.openjdk.java.net/browse/JDK-8020753
-        */
-       if (*stsize == 512 * 1024)
-               *stsize = 2048 * mono_pagesize ();
-#endif
-
-       /* staddr points to the start of the stack, not the end */
-       *staddr -= *stsize;
-
-       /* When running under emacs, sometimes staddr is not aligned to a page size */
-       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize() - 1));
-       return;
-
-#elif (defined(HAVE_PTHREAD_GETATTR_NP) || defined(HAVE_PTHREAD_ATTR_GET_NP)) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
-       /* Linux, BSD */
-
-       pthread_attr_t attr;
-       guint8 *current = (guint8*)&attr;
-
-       *staddr = NULL;
-       *stsize = (size_t)-1;
-
-       pthread_attr_init (&attr);
-
-#if     defined(HAVE_PTHREAD_GETATTR_NP)
-       /* Linux */
-       pthread_getattr_np (pthread_self(), &attr);
-
-#elif   defined(HAVE_PTHREAD_ATTR_GET_NP)
-       /* BSD */
-       pthread_attr_get_np (pthread_self(), &attr);
-
-#else
-#error         Cannot determine which API is needed to retrieve pthread attributes.
-#endif
-
-       pthread_attr_getstack (&attr, (void**)staddr, stsize);
-       pthread_attr_destroy (&attr);
-
-       if (*staddr)
-               g_assert ((current > *staddr) && (current < *staddr + *stsize));
-
-       /* When running under emacs, sometimes staddr is not aligned to a page size */
-       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
-       return;
-
-#elif defined(__OpenBSD__)
-       /* OpenBSD */
-       /* TODO :   Determine if this code is actually still needed. It may already be covered by the case above. */
-
-       pthread_attr_t attr;
-       guint8 *current = (guint8*)&attr;
-
-       *staddr = NULL;
-       *stsize = (size_t)-1;
-
-       pthread_attr_init (&attr);
-
-       stack_t ss;
-       int rslt;
-
-       rslt = pthread_stackseg_np(pthread_self(), &ss);
-       g_assert (rslt == 0);
+       MonoThread *thread;
+       MonoInternalThread *internal;
+       StartInfo *start_info;
+       gboolean res;
 
-       *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
-       *stsize = ss.ss_size;
+       thread = create_thread_object (domain);
+       internal = create_internal_thread ();
+       MONO_OBJECT_SETREF (thread, internal_thread, internal);
 
-       pthread_attr_destroy (&attr);
+       start_info = g_new0 (StartInfo, 1);
+       start_info->func = func;
+       start_info->obj = thread;
+       start_info->start_arg = arg;
 
-       if (*staddr)
-               g_assert ((current > *staddr) && (current < *staddr + *stsize));
+       res = create_thread (thread, internal, start_info, threadpool_thread, no_detach, stack_size, TRUE);
+       if (!res)
+               return NULL;
 
-       /* When running under emacs, sometimes staddr is not aligned to a page size */
-       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
-       return;
+       /* Check that the managed and unmanaged layout of MonoInternalThread matches */
+       if (mono_check_corlib_version () == NULL)
+               g_assert (((char*)&internal->unused2 - (char*)internal) == mono_defaults.internal_thread_class->fields [mono_defaults.internal_thread_class->field.count - 1].offset);
 
-#elif defined(sun) || defined(__native_client__)
-       /* Solaris/Illumos, NaCl */
-       pthread_attr_t attr;
-       pthread_attr_init (&attr);
-       pthread_attr_getstacksize (&attr, &stsize);
-       pthread_attr_destroy (&attr);
-       *staddr = NULL;
-       return;
+       return internal;
+}
 
-#else
-       /* FIXME:   It'd be better to use the 'error' preprocessor macro here so we know
-                   at compile-time if the target platform isn't supported. */
-#warning "Unable to determine how to retrieve a thread's stack-bounds for this platform in 'mono_thread_get_stack_bounds()'."
-       *staddr = NULL;
-       *stsize = 0;
-       return;
-#endif
+void
+mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
+{
+       mono_thread_create_internal (domain, func, arg, FALSE, FALSE, 0);
 }
 
 MonoThread *
@@ -975,7 +852,7 @@ mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
                g_error ("Thread %"G_GSIZE_FORMAT" calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThreadId ());
        }
 
-       thread = create_internal_thread_object ();
+       thread = create_internal_thread ();
 
        thread_handle = GetCurrentThread ();
        g_assert (thread_handle);
@@ -994,18 +871,8 @@ mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
 #ifdef PLATFORM_ANDROID
        thread->android_tid = (gpointer) gettid ();
 #endif
-       thread->apartment_state=ThreadApartmentState_Unknown;
-       thread->managed_id = get_next_managed_thread_id ();
-       if (mono_gc_is_moving ()) {
-               thread->thread_pinning_ref = thread;
-               MONO_GC_REGISTER_ROOT_PINNING (thread->thread_pinning_ref);
-       }
-
        thread->stack_ptr = &tid;
 
-       thread->synch_cs = g_new0 (CRITICAL_SECTION, 1);
-       InitializeCriticalSection (thread->synch_cs);
-
        THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
 
        info = mono_thread_info_current ();
@@ -1038,7 +905,7 @@ mono_thread_attach_full (MonoDomain *domain, gboolean force_attach)
                guint8 *staddr;
                size_t stsize;
 
-               mono_thread_get_stack_bounds (&staddr, &stsize);
+               mono_thread_info_get_stack_bounds (&staddr, &stsize);
 
                if (staddr == NULL)
                        mono_thread_attach_cb (tid, &tid);
@@ -1090,23 +957,20 @@ mono_thread_exit ()
 void
 ves_icall_System_Threading_Thread_ConstructInternalThread (MonoThread *this)
 {
-       MonoInternalThread *internal = create_internal_thread_object ();
+       MonoInternalThread *internal = create_internal_thread ();
 
        internal->state = ThreadState_Unstarted;
-       internal->apartment_state = ThreadApartmentState_Unknown;
-       internal->managed_id = get_next_managed_thread_id ();
 
        InterlockedCompareExchangePointer ((gpointer)&this->internal_thread, internal, NULL);
 }
 
-HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
-                                                        MonoObject *start)
+HANDLE
+ves_icall_System_Threading_Thread_Thread_internal (MonoThread *this,
+                                                                                                  MonoObject *start)
 {
-       guint32 (*start_func)(void *);
-       struct StartInfo *start_info;
-       HANDLE thread;
-       gsize tid;
+       StartInfo *start_info;
        MonoInternalThread *internal;
+       gboolean res;
 
        THREAD_DEBUG (g_message("%s: Trying to start a new thread: this (%p) start (%p)", __func__, this, start));
 
@@ -1114,84 +978,47 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                ves_icall_System_Threading_Thread_ConstructInternalThread (this);
        internal = this->internal_thread;
 
-       ensure_synch_cs_set (internal);
-
-       EnterCriticalSection (internal->synch_cs);
+       LOCK_THREAD (internal);
 
        if ((internal->state & ThreadState_Unstarted) == 0) {
-               LeaveCriticalSection (internal->synch_cs);
+               UNLOCK_THREAD (internal);
                mono_raise_exception (mono_get_exception_thread_state ("Thread has already been started."));
                return NULL;
        }
 
        if ((internal->state & ThreadState_Aborted) != 0) {
-               LeaveCriticalSection (internal->synch_cs);
+               UNLOCK_THREAD (internal);
                return this;
        }
-       start_func = NULL;
-       {
-               /* This is freed in start_wrapper */
-               start_info = g_new0 (struct StartInfo, 1);
-               start_info->func = start_func;
-               start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
-               start_info->delegate = start;
-               start_info->obj = this;
-               g_assert (this->obj.vtable->domain == mono_domain_get ());
-
-               internal->start_notify=CreateSemaphore (NULL, 0, 0x7fffffff, NULL);
-               if (internal->start_notify==NULL) {
-                       LeaveCriticalSection (internal->synch_cs);
-                       g_warning ("%s: CreateSemaphore error 0x%x", __func__, GetLastError ());
-                       g_free (start_info);
-                       return(NULL);
-               }
-
-               mono_threads_lock ();
-               register_thread_start_argument (this, start_info);
-               if (threads_starting_up == NULL) {
-                       MONO_GC_REGISTER_ROOT_FIXED (threads_starting_up);
-                       threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
-               }
-               mono_g_hash_table_insert (threads_starting_up, this, this);
-               mono_threads_unlock (); 
-
-               thread=mono_create_thread(NULL, default_stacksize_for_thread (internal), (LPTHREAD_START_ROUTINE)start_wrapper, start_info,
-                                   CREATE_SUSPENDED, &tid);
-               if(thread==NULL) {
-                       LeaveCriticalSection (internal->synch_cs);
-                       mono_threads_lock ();
-                       mono_g_hash_table_remove (threads_starting_up, this);
-                       mono_threads_unlock ();
-                       g_warning("%s: CreateThread error 0x%x", __func__, GetLastError());
-                       return(NULL);
-               }
-               
-               internal->handle=thread;
-               internal->tid=tid;
-               if (mono_gc_is_moving ()) {
-                       internal->thread_pinning_ref = internal;
-                       MONO_GC_REGISTER_ROOT_PINNING (internal->thread_pinning_ref);
-               }
-               
-
-               /* Don't call handle_store() here, delay it to Start.
-                * We can't join a thread (trying to will just block
-                * forever) until it actually starts running, so don't
-                * store the handle till then.
-                */
+       /* This is freed in start_wrapper */
+       start_info = g_new0 (StartInfo, 1);
+       start_info->func = NULL;
+       start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
+       start_info->delegate = start;
+       start_info->obj = this;
+       g_assert (this->obj.vtable->domain == mono_domain_get ());
+
+       res = create_thread (this, internal, start_info, FALSE, FALSE, 0, FALSE);
+       if (!res) {
+               UNLOCK_THREAD (internal);
+               return NULL;
+       }
 
-               mono_thread_start (this);
-               
-               internal->state &= ~ThreadState_Unstarted;
+       internal->state &= ~ThreadState_Unstarted;
 
-               THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
+       THREAD_DEBUG (g_message ("%s: Started thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread));
 
-               LeaveCriticalSection (internal->synch_cs);
-               return(thread);
-       }
+       UNLOCK_THREAD (internal);
+       return internal->handle;
 }
 
-void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
+/*
+ * This is called from the finalizer of the internal thread object. Since threads keep a reference to their
+ * thread object while running, by the time this function is called, the thread has already exited/detached,
+ * i.e. thread_cleanup () has ran.
+ */
+void
+ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread)
 {
        THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread));
 
@@ -1212,38 +1039,6 @@ void ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInterna
        }
 }
 
-static void mono_thread_start (MonoThread *thread)
-{
-       MonoInternalThread *internal = thread->internal_thread;
-
-       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
-
-       /* Only store the handle when the thread is about to be
-        * launched, to avoid the main thread deadlocking while trying
-        * to clean up a thread that will never be signalled.
-        */
-       if (!handle_store (thread, FALSE))
-               return;
-
-       ResumeThread (internal->handle);
-
-       if(internal->start_notify!=NULL) {
-               /* Wait for the thread to set up its TLS data etc, so
-                * theres no potential race condition if someone tries
-                * to look up the data believing the thread has
-                * started
-                */
-
-               THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") waiting for thread %p (%"G_GSIZE_FORMAT") to start", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
-
-               WaitForSingleObjectEx (internal->start_notify, INFINITE, FALSE);
-               CloseHandle (internal->start_notify);
-               internal->start_notify = NULL;
-       }
-
-       THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Done launching thread %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), internal, (gsize)internal->tid));
-}
-
 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
 {
        guint32 res;
@@ -1288,11 +1083,7 @@ ves_icall_System_Threading_Thread_GetDomainID (void)
 gboolean 
 ves_icall_System_Threading_Thread_Yield (void)
 {
-#ifdef HOST_WIN32
-       return SwitchToThread ();
-#else
-       return sched_yield () == 0;
-#endif
+       return mono_thread_info_yield ();
 }
 
 /*
@@ -1307,9 +1098,7 @@ mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
 {
        gunichar2 *res;
 
-       ensure_synch_cs_set (this_obj);
-       
-       EnterCriticalSection (this_obj->synch_cs);
+       LOCK_THREAD (this_obj);
        
        if (!this_obj->name) {
                *name_len = 0;
@@ -1320,7 +1109,7 @@ mono_thread_get_name (MonoInternalThread *this_obj, guint32 *name_len)
                memcpy (res, this_obj->name, sizeof (gunichar2) * this_obj->name_len);
        }
        
-       LeaveCriticalSection (this_obj->synch_cs);
+       UNLOCK_THREAD (this_obj);
 
        return res;
 }
@@ -1330,16 +1119,14 @@ ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj
 {
        MonoString* str;
 
-       ensure_synch_cs_set (this_obj);
-       
-       EnterCriticalSection (this_obj->synch_cs);
+       LOCK_THREAD (this_obj);
        
        if (!this_obj->name)
                str = NULL;
        else
                str = mono_string_new_utf16 (mono_domain_get (), this_obj->name, this_obj->name_len);
        
-       LeaveCriticalSection (this_obj->synch_cs);
+       UNLOCK_THREAD (this_obj);
        
        return str;
 }
@@ -1347,12 +1134,10 @@ ves_icall_System_Threading_Thread_GetName_internal (MonoInternalThread *this_obj
 void 
 mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, gboolean managed)
 {
-       ensure_synch_cs_set (this_obj);
-       
-       EnterCriticalSection (this_obj->synch_cs);
+       LOCK_THREAD (this_obj);
 
        if (this_obj->flags & MONO_THREAD_FLAG_NAME_SET) {
-               LeaveCriticalSection (this_obj->synch_cs);
+               UNLOCK_THREAD (this_obj);
                
                mono_raise_exception (mono_get_exception_invalid_operation ("Thread.Name can only be set once."));
                return;
@@ -1368,7 +1153,8 @@ mono_thread_set_name_internal (MonoInternalThread *this_obj, MonoString *name, g
        if (managed)
                this_obj->flags |= MONO_THREAD_FLAG_NAME_SET;
        
-       LeaveCriticalSection (this_obj->synch_cs);
+       UNLOCK_THREAD (this_obj);
+
        if (this_obj->name) {
                char *tname = mono_string_to_utf8 (name);
                mono_profiler_thread_name (this_obj->tid, tname);
@@ -1445,18 +1231,16 @@ gboolean ves_icall_System_Threading_Thread_Join_internal(MonoInternalThread *thi
 
        mono_thread_current_check_pending_interrupt ();
 
-       ensure_synch_cs_set (this);
-       
-       EnterCriticalSection (this->synch_cs);
+       LOCK_THREAD (this);
        
        if ((this->state & ThreadState_Unstarted) != 0) {
-               LeaveCriticalSection (this->synch_cs);
+               UNLOCK_THREAD (this);
                
                mono_raise_exception (mono_get_exception_thread_state ("Thread has not been started."));
                return FALSE;
        }
 
-       LeaveCriticalSection (this->synch_cs);
+       UNLOCK_THREAD (this);
 
        if(ms== -1) {
                ms=INFINITE;
@@ -2052,13 +1836,11 @@ ves_icall_System_Threading_Thread_GetState (MonoInternalThread* this)
 {
        guint32 state;
 
-       ensure_synch_cs_set (this);
-       
-       EnterCriticalSection (this->synch_cs);
+       LOCK_THREAD (this);
        
        state = this->state;
 
-       LeaveCriticalSection (this->synch_cs);
+       UNLOCK_THREAD (this);
        
        return state;
 }
@@ -2068,16 +1850,14 @@ void ves_icall_System_Threading_Thread_Interrupt_internal (MonoInternalThread *t
        MonoInternalThread *current;
        gboolean throw;
 
-       ensure_synch_cs_set (this);
+       LOCK_THREAD (this);
 
        current = mono_thread_internal_current ();
 
-       EnterCriticalSection (this->synch_cs);  
-
        this->thread_interrupt_requested = TRUE;        
        throw = current != this && (this->state & ThreadState_WaitSleepJoin);   
 
-       LeaveCriticalSection (this->synch_cs);
+       UNLOCK_THREAD (this);
        
        if (throw) {
                abort_thread_internal (this, TRUE, FALSE);
@@ -2089,16 +1869,14 @@ void mono_thread_current_check_pending_interrupt ()
        MonoInternalThread *thread = mono_thread_internal_current ();
        gboolean throw = FALSE;
 
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        
        if (thread->thread_interrupt_requested) {
                throw = TRUE;
                thread->thread_interrupt_requested = FALSE;
        }
        
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 
        if (throw) {
                mono_raise_exception (mono_get_exception_thread_interrupted ());
@@ -2180,21 +1958,19 @@ static void signal_thread_state_change (MonoInternalThread *thread)
 void
 ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject *state)
 {
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        
        if ((thread->state & ThreadState_AbortRequested) != 0 || 
                (thread->state & ThreadState_StopRequested) != 0 ||
                (thread->state & ThreadState_Stopped) != 0)
        {
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return;
        }
 
        if ((thread->state & ThreadState_Unstarted) != 0) {
                thread->state |= ThreadState_Aborted;
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return;
        }
 
@@ -2217,7 +1993,7 @@ ves_icall_System_Threading_Thread_Abort (MonoInternalThread *thread, MonoObject
         * a problem.
         */
 
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 
        THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Abort requested for %p (%"G_GSIZE_FORMAT")", __func__, GetCurrentThreadId (), thread, (gsize)thread->tid));
 
@@ -2235,12 +2011,10 @@ ves_icall_System_Threading_Thread_ResetAbort (void)
        MonoInternalThread *thread = mono_thread_internal_current ();
        gboolean was_aborting;
 
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        was_aborting = thread->state & ThreadState_AbortRequested;
        thread->state &= ~ThreadState_AbortRequested;
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 
        if (!was_aborting) {
                const char *msg = "Unable to reset abort because no abort was requested";
@@ -2258,9 +2032,7 @@ ves_icall_System_Threading_Thread_ResetAbort (void)
 void
 mono_thread_internal_reset_abort (MonoInternalThread *thread)
 {
-       ensure_synch_cs_set (thread);
-
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
 
        thread->state &= ~ThreadState_AbortRequested;
 
@@ -2274,7 +2046,7 @@ mono_thread_internal_reset_abort (MonoInternalThread *thread)
                }
        }
 
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 }
 
 MonoObject*
@@ -2309,15 +2081,13 @@ ves_icall_System_Threading_Thread_GetAbortExceptionState (MonoThread *this)
 static gboolean
 mono_thread_suspend (MonoInternalThread *thread)
 {
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
 
        if ((thread->state & ThreadState_Unstarted) != 0 || 
                (thread->state & ThreadState_Aborted) != 0 || 
                (thread->state & ThreadState_Stopped) != 0)
        {
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return FALSE;
        }
 
@@ -2325,13 +2095,13 @@ mono_thread_suspend (MonoInternalThread *thread)
                (thread->state & ThreadState_SuspendRequested) != 0 ||
                (thread->state & ThreadState_StopRequested) != 0) 
        {
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return TRUE;
        }
        
        thread->state |= ThreadState_SuspendRequested;
 
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 
        suspend_thread_internal (thread, FALSE);
        return TRUE;
@@ -2347,13 +2117,11 @@ ves_icall_System_Threading_Thread_Suspend (MonoInternalThread *thread)
 static gboolean
 mono_thread_resume (MonoInternalThread *thread)
 {
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
 
        if ((thread->state & ThreadState_SuspendRequested) != 0) {
                thread->state &= ~ThreadState_SuspendRequested;
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return TRUE;
        }
 
@@ -2362,7 +2130,7 @@ mono_thread_resume (MonoInternalThread *thread)
                (thread->state & ThreadState_Aborted) != 0 || 
                (thread->state & ThreadState_Stopped) != 0)
        {
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return FALSE;
        }
 
@@ -2411,14 +2179,12 @@ is_running_protected_wrapper (void)
 
 void mono_thread_internal_stop (MonoInternalThread *thread)
 {
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
 
        if ((thread->state & ThreadState_StopRequested) != 0 ||
                (thread->state & ThreadState_Stopped) != 0)
        {
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return;
        }
        
@@ -2428,7 +2194,7 @@ void mono_thread_internal_stop (MonoInternalThread *thread)
        thread->state |= ThreadState_StopRequested;
        thread->state &= ~ThreadState_AbortRequested;
        
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
        
        abort_thread_internal (thread, TRUE, TRUE);
 }
@@ -2998,16 +2764,16 @@ mono_threads_set_shutting_down (void)
 
                /* Make sure we're properly suspended/stopped */
 
-               EnterCriticalSection (current_thread->synch_cs);
+               LOCK_THREAD (current_thread);
 
                if ((current_thread->state & ThreadState_SuspendRequested) ||
                    (current_thread->state & ThreadState_AbortRequested) ||
                    (current_thread->state & ThreadState_StopRequested)) {
-                       LeaveCriticalSection (current_thread->synch_cs);
+                       UNLOCK_THREAD (current_thread);
                        mono_thread_execute_interruption (current_thread);
                } else {
                        current_thread->state |= ThreadState_Stopped;
-                       LeaveCriticalSection (current_thread->synch_cs);
+                       UNLOCK_THREAD (current_thread);
                }
 
                /*since we're killing the thread, unset the current domain.*/
@@ -3102,7 +2868,7 @@ void mono_thread_manage (void)
         * This could be removed if we avoid pthread_detach() and use pthread_join().
         */
 #ifndef HOST_WIN32
-       sched_yield ();
+       mono_thread_info_yield ();
 #endif
 }
 
@@ -3218,15 +2984,13 @@ void mono_thread_suspend_all_other_threads (void)
                                continue;
                        }
 
-                       ensure_synch_cs_set (thread);
-               
-                       EnterCriticalSection (thread->synch_cs);
+                       LOCK_THREAD (thread);
 
                        if (thread->suspended_event == NULL) {
                                thread->suspended_event = CreateEvent (NULL, TRUE, FALSE, NULL);
                                if (thread->suspended_event == NULL) {
                                        /* Forget this one and go on to the next */
-                                       LeaveCriticalSection (thread->synch_cs);
+                                       UNLOCK_THREAD (thread);
                                        continue;
                                }
                        }
@@ -3234,7 +2998,7 @@ void mono_thread_suspend_all_other_threads (void)
                        if ((thread->state & ThreadState_Suspended) != 0 || 
                                (thread->state & ThreadState_StopRequested) != 0 ||
                                (thread->state & ThreadState_Stopped) != 0) {
-                               LeaveCriticalSection (thread->synch_cs);
+                               UNLOCK_THREAD (thread);
                                CloseHandle (wait->handles [i]);
                                wait->threads [i] = NULL; /* ignore this thread in next loop */
                                continue;
@@ -3251,7 +3015,7 @@ void mono_thread_suspend_all_other_threads (void)
                        
                        thread->state |= ThreadState_SuspendRequested;
 
-                       LeaveCriticalSection (thread->synch_cs);
+                       UNLOCK_THREAD (thread);
 
                        /* Signal the thread to suspend */
                        if (mono_thread_info_new_interrupt_enabled ())
@@ -3269,14 +3033,12 @@ void mono_thread_suspend_all_other_threads (void)
                                if (thread == NULL)
                                        continue;
 
-                               ensure_synch_cs_set (thread);
-                       
-                               EnterCriticalSection (thread->synch_cs);
+                               LOCK_THREAD (thread);
                                if ((thread->state & ThreadState_Suspended) != 0) {
                                        CloseHandle (thread->suspended_event);
                                        thread->suspended_event = NULL;
                                }
-                               LeaveCriticalSection (thread->synch_cs);
+                               UNLOCK_THREAD (thread);
                        }
                }
                
@@ -3911,6 +3673,7 @@ search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32
                                static_data->freelist = tmp->next;
                        return tmp;
                }
+               prev = tmp;
                tmp = tmp->next;
        }
        return NULL;
@@ -4233,11 +3996,6 @@ mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
 static void CALLBACK dummy_apc (ULONG_PTR param)
 {
 }
-#else
-static guint32 dummy_apc (gpointer param)
-{
-       return 0;
-}
 #endif
 
 /*
@@ -4248,9 +4006,7 @@ static guint32 dummy_apc (gpointer param)
  */
 static MonoException* mono_thread_execute_interruption (MonoInternalThread *thread)
 {
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
 
        /* MonoThread::interruption_requested can only be changed with atomics */
        if (InterlockedCompareExchange (&thread->interruption_requested, FALSE, TRUE)) {
@@ -4264,7 +4020,7 @@ static MonoException* mono_thread_execute_interruption (MonoInternalThread *thre
        }
 
        if ((thread->state & ThreadState_AbortRequested) != 0) {
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                if (thread->abort_exc == NULL) {
                        /* 
                         * This might be racy, but it has to be called outside the lock
@@ -4281,7 +4037,7 @@ static MonoException* mono_thread_execute_interruption (MonoInternalThread *thre
        else if ((thread->state & ThreadState_StopRequested) != 0) {
                /* FIXME: do this through the JIT? */
 
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                
                mono_thread_exit ();
                return NULL;
@@ -4291,17 +4047,17 @@ static MonoException* mono_thread_execute_interruption (MonoInternalThread *thre
                exc = thread->pending_exception;
                thread->pending_exception = NULL;
 
-        LeaveCriticalSection (thread->synch_cs);
+        UNLOCK_THREAD (thread);
         return exc;
        } else if (thread->thread_interrupt_requested) {
 
                thread->thread_interrupt_requested = FALSE;
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                
                return(mono_get_exception_thread_interrupted ());
        }
        
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
        
        return NULL;
 }
@@ -4338,7 +4094,6 @@ mono_thread_request_interruption (gboolean running_managed)
                /* Can't stop while in unmanaged code. Increase the global interruption
                   request count. When exiting the unmanaged method the count will be
                   checked and the thread will be interrupted. */
-               
 
                if (mono_thread_notify_pending_exc_fn && !running_managed)
                        /* The JIT will notify the thread about the interruption */
@@ -4348,7 +4103,11 @@ mono_thread_request_interruption (gboolean running_managed)
                /* this will awake the thread if it is in WaitForSingleObject 
                   or similar */
                /* Our implementation of this function ignores the func argument */
+#ifdef HOST_WIN32
                QueueUserAPC ((PAPCFUNC)dummy_apc, thread->handle, NULL);
+#else
+               wapi_thread_interrupt_self ();
+#endif
                return NULL;
        }
        else {
@@ -4368,10 +4127,9 @@ mono_thread_resume_interruption (void)
        if (thread == NULL)
                return NULL;
 
-       ensure_synch_cs_set (thread);
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 
        /*This can happen if the protected block called Thread::ResetAbort*/
        if (!still_aborting)
@@ -4526,21 +4284,17 @@ mono_thread_cleanup_apartment_state (void)
 void
 mono_thread_set_state (MonoInternalThread *thread, MonoThreadState state)
 {
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        thread->state |= state;
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 }
 
 void
 mono_thread_clr_state (MonoInternalThread *thread, MonoThreadState state)
 {
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        thread->state &= ~state;
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 }
 
 gboolean
@@ -4548,15 +4302,13 @@ mono_thread_test_state (MonoInternalThread *thread, MonoThreadState test)
 {
        gboolean ret = FALSE;
 
-       ensure_synch_cs_set (thread);
-       
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
 
        if ((thread->state & test) != 0) {
                ret = TRUE;
        }
        
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
        
        return ret;
 }
@@ -4771,7 +4523,7 @@ transition_to_suspended (MonoInternalThread *thread)
                thread->state |= ThreadState_Suspended;
                mono_thread_info_finish_suspend ();
        }
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
 }
 
 static void
@@ -4782,7 +4534,7 @@ suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt)
                return;
        }
 
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        if (thread == mono_thread_internal_current ()) {
                transition_to_suspended (thread);
                mono_thread_info_self_suspend ();
@@ -4794,7 +4546,7 @@ suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt)
 
                /*A null info usually means the thread is already dead. */
                if (!(info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gsize)thread->tid, interrupt))) {
-                       LeaveCriticalSection (thread->synch_cs);
+                       UNLOCK_THREAD (thread);
                        return;
                }
 
@@ -4818,7 +4570,7 @@ suspend_thread_internal (MonoInternalThread *thread, gboolean interrupt)
                        if (interrupt)
                                wapi_finish_interrupt_thread (interrupt_handle);
 #endif
-                       LeaveCriticalSection (thread->synch_cs);
+                       UNLOCK_THREAD (thread);
                }
        }
 }
@@ -4832,13 +4584,13 @@ self_suspend_internal (MonoInternalThread *thread)
                thread->state |= ThreadState_Suspended;
                thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
                if (thread->suspend_event == NULL) {
-                       LeaveCriticalSection (thread->synch_cs);
+                       UNLOCK_THREAD (thread);
                        return;
                }
                if (thread->suspended_event)
                        SetEvent (thread->suspended_event);
 
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
 
                if (shutting_down) {
                        /* After we left the lock, the runtime might shut down so everything becomes invalid */
@@ -4848,7 +4600,7 @@ self_suspend_internal (MonoInternalThread *thread)
                
                WaitForSingleObject (thread->suspend_event, INFINITE);
                
-               EnterCriticalSection (thread->synch_cs);
+               LOCK_THREAD (thread);
 
                CloseHandle (thread->suspend_event);
                thread->suspend_event = NULL;
@@ -4859,7 +4611,7 @@ self_suspend_internal (MonoInternalThread *thread)
                 */
                SetEvent (thread->resume_event);
 
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
                return;
        }
 
@@ -4874,14 +4626,14 @@ resume_thread_internal (MonoInternalThread *thread)
        if (!mono_thread_info_new_interrupt_enabled ()) {
                thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
                if (thread->resume_event == NULL) {
-                       LeaveCriticalSection (thread->synch_cs);
+                       UNLOCK_THREAD (thread);
                        return FALSE;
                }
 
                /* Awake the thread */
                SetEvent (thread->suspend_event);
 
-               LeaveCriticalSection (thread->synch_cs);
+               UNLOCK_THREAD (thread);
 
                /* Wait for the thread to awake */
                WaitForSingleObject (thread->resume_event, INFINITE);
@@ -4890,13 +4642,13 @@ resume_thread_internal (MonoInternalThread *thread)
                return TRUE;
        }
 
-       LeaveCriticalSection (thread->synch_cs);        
+       UNLOCK_THREAD (thread);
        /* Awake the thread */
        if (!mono_thread_info_resume ((MonoNativeThreadId)(gpointer)(gsize)thread->tid))
                return FALSE;
-       EnterCriticalSection (thread->synch_cs);
+       LOCK_THREAD (thread);
        thread->state &= ~ThreadState_Suspended;
-       LeaveCriticalSection (thread->synch_cs);
+       UNLOCK_THREAD (thread);
        return TRUE;
 }
 
index 8be85bc538898e693ef880940239249f9e678f99..25b89a44b7a664e0e96b36c314e0ff8d28722aa2 100755 (executable)
@@ -406,6 +406,7 @@ common_sources = \
        tasklets.c              \
        tasklets.h              \
        simd-intrinsics.c       \
+       mini-native-types.c \
        mini-unwind.h           \
        unwind.c                \
        image-writer.h          \
index ef164426e6179903d825e89cc4beee8d450f361e..9289285c95aef03e3e526f33054426e90a15a5c8 100644 (file)
@@ -14,6 +14,8 @@
 #include "ir-emit.h"
 #include "glib.h"
 
+#ifndef DISABLE_JIT
+
 static gboolean
 is_int_stack_size (int type)
 {
@@ -333,3 +335,5 @@ done:
        if (cfg->verbose_level > 2)
                mono_print_code (cfg, "AFTER ALIAS_ANALYSIS");
 }
+
+#endif /* !DISABLE_JIT */
index 4f66e3997fa40fdb895a10c0c90eba0ae1863353..b7ae72bd6d54f7115f5569d9de821dfe9b8160b6 100755 (executable)
@@ -5014,9 +5014,9 @@ encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint
                int i;
 
                encode_method_ref (acfg, info->method, p, &p);
-               encode_value (info->entries->len, p, &p);
-               for (i = 0; i < info->entries->len; ++i) {
-                       MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
+               encode_value (info->num_entries, p, &p);
+               for (i = 0; i < info->num_entries; ++i) {
+                       MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
 
                        encode_value (template->info_type, p, &p);
                        switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
@@ -6481,7 +6481,7 @@ compile_method (MonoAotCompile *acfg, MonoMethod *method)
         * the runtime will not see AOT methods during AOT compilation,so it
         * does not need to support them by creating a fake GOT etc.
         */
-       cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
+       cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), acfg->aot_opts.full_aot ? (JIT_FLAG_AOT|JIT_FLAG_FULL_AOT) : (JIT_FLAG_AOT), 0);
        mono_loader_clear_error ();
 
        if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
@@ -8386,7 +8386,7 @@ compile_methods (MonoAotCompile *acfg)
                        user_data [1] = acfg;
                        user_data [2] = frag;
                        
-                       handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
+                       handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
                        g_ptr_array_add (threads, handle);
                }
                g_free (methods);
@@ -8420,7 +8420,7 @@ compile_asm (MonoAotCompile *acfg)
 #elif defined(sparc) && SIZEOF_VOID_P == 8
 #define AS_OPTIONS "-xarch=v9"
 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
-#define AS_OPTIONS "-arch i386 -W"
+#define AS_OPTIONS "-arch i386"
 #else
 #define AS_OPTIONS ""
 #endif
@@ -8652,7 +8652,7 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
        TV_DECLARE (atv);
        TV_DECLARE (btv);
 
-#if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || (!defined(MONO_EXTENSIONS) && !defined(MONOTOUCH))
+#if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(MONO_GSHARING)
        if (opts & MONO_OPT_GSHAREDVT) {
                fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
                exit (1);
@@ -8902,8 +8902,10 @@ mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
        if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
                /*
                 * CLANG supports GAS .file/.loc directives, so emit line number information this way
+                * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
+                * .byte directives.
                 */
-               acfg->gas_line_numbers = TRUE;
+               //acfg->gas_line_numbers = TRUE;
        }
 
        if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
index 32bbeb79b46be1734bed82dd82871164ae42810a..51577f520cea1f45e4df06e12f873e1f19dd5dd0 100644 (file)
@@ -3121,7 +3121,7 @@ decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guin
                ji->data.target = GINT_TO_POINTER (decode_value (p, &p));
                break;
        case MONO_PATCH_INFO_GSHAREDVT_CALL: {
-               MonoJumpInfoGSharedVtCall *info = g_new0 (MonoJumpInfoGSharedVtCall, 1);
+               MonoJumpInfoGSharedVtCall *info = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoGSharedVtCall));
                info->sig = decode_signature (aot_module, p, &p);
                g_assert (info->sig);
                info->method = decode_resolve_method_ref (aot_module, p, &p);
@@ -3131,15 +3131,16 @@ decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guin
                break;
        }
        case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
-               MonoGSharedVtMethodInfo *info = g_new0 (MonoGSharedVtMethodInfo, 1);
-               int i, nentries;
+               MonoGSharedVtMethodInfo *info = mono_mempool_alloc0 (mp, sizeof (MonoGSharedVtMethodInfo));
+               int i;
                
                info->method = decode_resolve_method_ref (aot_module, p, &p);
                g_assert (info->method);
-               nentries = decode_value (p, &p);
-               info->entries = g_ptr_array_new ();
-               for (i = 0; i < nentries; ++i) {
-                       MonoRuntimeGenericContextInfoTemplate *template = g_new0 (MonoRuntimeGenericContextInfoTemplate, 1);
+               info->num_entries = decode_value (p, &p);
+               info->count_entries = info->num_entries;
+               info->entries = mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
+               for (i = 0; i < info->num_entries; ++i) {
+                       MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
 
                        template->info_type = decode_value (p, &p);
                        switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
@@ -3159,8 +3160,6 @@ decode_patch (MonoAotModule *aot_module, MonoMemPool *mp, MonoJumpInfo *ji, guin
                                g_assert_not_reached ();
                                break;
                        }
-
-                       g_ptr_array_add (info->entries, template);
                }
                ji->data.target = info;
                break;
@@ -3641,15 +3640,8 @@ mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
                        MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
 
                        code = mono_aot_get_method (domain, m);
-                       if (code) {
-                               if (mono_method_needs_static_rgctx_invoke (m, FALSE)) {
-                                       code = mono_create_static_rgctx_trampoline (m, mono_create_ftnptr (domain, code));
-                                       /* The call above returns an ftnptr */
-                                       code = mono_get_addr_from_ftnptr (code);
-                               }
-
+                       if (code)
                                return code;
-                       }
                }
 
                /*
index 329f70a52a9a1faa3e74690334cf5dbfcfaacbcf..0036db0b42e35d59446f942a28c6941448132fa7 100644 (file)
@@ -65,7 +65,7 @@ break: len:2
 tailcall: len:120 clob:c
 br: len:6
 label: len:0
-seq_point: len:31
+seq_point: len:31 clob:c
 
 long_add: dest:i src1:i src2:i len:3 clob:1 nacl:6
 long_sub: dest:i src1:i src2:i len:3 clob:1 nacl:6
index 4b509eb31b90b2369b856f7879b20ff3bcd27802..e5c40fd6dba930e0de9720858f39177fa4d936e7 100755 (executable)
@@ -1576,9 +1576,7 @@ stop_debugger_thread (void)
 static void
 start_debugger_thread (void)
 {
-       gsize tid;
-
-       debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
+       debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
        g_assert (debugger_thread_handle);
 }
 
@@ -6020,6 +6018,16 @@ set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domai
                mgreg_t v;
                gboolean is_signed = FALSE;
 
+               if (t->byref) {
+                       addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
+
+                       if (addr) {
+                               // FIXME: Write barriers
+                               mono_gc_memmove (addr, val, size);
+                       }
+                       break;
+               }
+
                if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
                        is_signed = TRUE;
 
@@ -6040,9 +6048,6 @@ set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domai
                        g_assert_not_reached ();
                }
 
-               if (t->byref)
-                       NOT_IMPLEMENTED;
-
                /* Set value on the stack or in the return ctx */
                if (reg_locations [reg]) {
                        /* Saved on the stack */
index 70dde3c406360dd67aa22d76b6075b1f04998560..3d7f5d8860c7b67b7a554a83d7d44fc82ce80be5 100644 (file)
@@ -386,7 +386,7 @@ mini_regression_step (MonoImage *image, int verbose, int *total_run, int *total,
                        run++;
                        start_time = g_timer_elapsed (timer, NULL);
                        comp_time -= start_time;
-                       cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), TRUE, FALSE, 0);
+                       cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, opt_flags), mono_get_root_domain (), JIT_FLAG_RUN_CCTORS, 0);
                        comp_time += g_timer_elapsed (timer, NULL);
                        if (cfg->exception_type == MONO_EXCEPTION_NONE) {
                                if (verbose >= 2)
@@ -935,7 +935,7 @@ compile_all_methods_thread_main_inner (CompileAllThreadArgs *args)
                        g_print ("Compiling %d %s\n", count, desc);
                        g_free (desc);
                }
-               cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), FALSE, FALSE, 0);
+               cfg = mini_method_compile (method, mono_get_optimizations_for_method (method, args->opts), mono_get_root_domain (), 0, 0);
                if (cfg->exception_type != MONO_EXCEPTION_NONE) {
                        printf ("Compilation of %s failed with exception '%s':\n", mono_method_full_name (cfg->method, TRUE), cfg->exception_message);
                        fail_count ++;
@@ -1542,7 +1542,7 @@ mono_main (int argc, char* argv[])
                        char *build = mono_get_runtime_build_info ();
                        char *gc_descr;
 
-                       g_print ("Mono Runtime Engine version %s\nCopyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
+                       g_print ("Mono JIT compiler version %s\nCopyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com\n", build);
                        g_free (build);
                        g_print (info);
                        gc_descr = mono_gc_get_description ();
@@ -2086,10 +2086,10 @@ mono_main (int argc, char* argv[])
                        (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
                        MonoMethod *nm;
                        nm = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
-                       cfg = mini_method_compile (nm, opt, mono_get_root_domain (), FALSE, FALSE, part);
+                       cfg = mini_method_compile (nm, opt, mono_get_root_domain (), 0, part);
                }
                else
-                       cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, part);
+                       cfg = mini_method_compile (method, opt, mono_get_root_domain (), 0, part);
                if ((mono_graph_options & MONO_GRAPH_CFG_SSA) && !(cfg->comp_done & MONO_COMP_SSA)) {
                        g_warning ("no SSA info available (use -O=deadce)");
                        return 1;
@@ -2121,7 +2121,7 @@ mono_main (int argc, char* argv[])
                                opt = opt_sets [i];
                                g_timer_start (timer);
                                for (j = 0; j < count; ++j) {
-                                       cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
+                                       cfg = mini_method_compile (method, opt, mono_get_root_domain (), 0, 0);
                                        mono_destroy_compile (cfg);
                                }
                                g_timer_stop (timer);
@@ -2144,12 +2144,12 @@ mono_main (int argc, char* argv[])
                                        (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
                                        method = mono_marshal_get_native_wrapper (method, TRUE, FALSE);
 
-                               cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
+                               cfg = mini_method_compile (method, opt, mono_get_root_domain (), 0, 0);
                                mono_destroy_compile (cfg);
                        }
                }
        } else {
-               cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
+               cfg = mini_method_compile (method, opt, mono_get_root_domain (), 0, 0);
                mono_destroy_compile (cfg);
        }
 #endif
index c8acff20d24a44ea16ab5d8b7996f7680e76a118..7542f49aa75d234f995cf7834b667a5f00bb3d9a 100644 (file)
@@ -675,69 +675,6 @@ add_line_number_file_name (MonoDwarfWriter *w, const char *name,
        return index;
 }
 
-static void
-emit_line_number_info_begin (MonoDwarfWriter *w)
-{
-       /* Line number info header */
-       /* 
-        * GAS seems to emit its own data to the end of the first subsection, so we use
-        * subsections 1, 2 etc:
-        * 1 - contains the header
-        * 2 - contains the file names
-        * 3 - contains the end of the header + the data
-        * 4 - the end symbol
-        */
-       emit_section_change (w, ".debug_line", 0);
-       emit_label (w, ".Ldebug_line_section_start");
-       emit_section_change (w, ".debug_line", LINE_SUBSECTION_HEADER);
-       emit_label (w, ".Ldebug_line_start");
-       emit_symbol_diff (w, ".Ldebug_line_end", ".", -4); /* length */
-       emit_int16 (w, 0x2); /* version */
-       emit_symbol_diff (w, ".Ldebug_line_header_end", ".", -4); /* header_length */
-       emit_byte (w, 1); /* minimum_instruction_length */
-       emit_byte (w, 1); /* default_is_stmt */
-       emit_byte (w, LINE_BASE); /* line_base */
-       emit_byte (w, LINE_RANGE); /* line_range */
-       emit_byte (w, OPCODE_BASE); /* opcode_base */
-       emit_byte (w, 0); /* standard_opcode_lengths */
-       emit_byte (w, 1);
-       emit_byte (w, 1);
-       emit_byte (w, 1);
-       emit_byte (w, 1);
-       emit_byte (w, 0);
-       emit_byte (w, 0);
-       emit_byte (w, 0);
-       emit_byte (w, 1);
-       emit_byte (w, 0);
-       emit_byte (w, 0);
-       emit_byte (w, 1);
-
-       /* Includes */
-       emit_section_change (w, ".debug_line", LINE_SUBSECTION_INCLUDES);
-
-       /* End of Includes */
-       emit_section_change (w, ".debug_line", LINE_SUBSECTION_FILES);
-       emit_byte (w, 0);
-
-       /* Files */
-       emit_line_number_file_name (w, "xdb.il", 0, 0);
-
-       /* End of Files */
-       emit_section_change (w, ".debug_line", LINE_SUBSECTION_DATA);
-       emit_byte (w, 0);
-
-       emit_label (w, ".Ldebug_line_header_end");
-
-       /* Emit this into a separate subsection so it gets placed at the end */ 
-       emit_section_change (w, ".debug_line", LINE_SUBSECTION_END);
-
-       emit_byte (w, 0);
-       emit_byte (w, 1);
-       emit_byte (w, DW_LNE_end_sequence);
-
-       emit_label (w, ".Ldebug_line_end");
-}
-
 char *
 mono_dwarf_escape_path (const char *name)
 {
@@ -1678,6 +1615,7 @@ emit_line_number_info (MonoDwarfWriter *w, MonoMethod *method,
        prev_line = 1;
        prev_il_offset = -1;
 
+       w->cur_file_index = -1;
        for (i = 0; i < code_size; ++i) {
                int line_diff, addr_diff;
 
@@ -1731,8 +1669,6 @@ emit_line_number_info (MonoDwarfWriter *w, MonoMethod *method,
                        emit_byte (w, DW_LNS_advance_line);
                        //printf ("FIRST: %d %d %d\n", prev_line, loc->row, il_offset);
                        emit_sleb128 (w, (gint32)loc->row - (gint32)prev_line);
-                       prev_line = loc->row;
-                       prev_native_offset = i;
                        first = FALSE;
                }
 
@@ -1754,6 +1690,9 @@ emit_line_number_info (MonoDwarfWriter *w, MonoMethod *method,
                                        w->cur_file_index = file_index;
                                }                                       
                        }
+               }
+
+               if (loc->row != prev_line && !first) {
                        //printf ("X: %p(+0x%x) %d %s:%d(+%d)\n", code + i, addr_diff, loc->il_offset, loc->source_file, loc->row, line_diff);
                        emit_advance_op (w, line_diff, addr_diff);
 
@@ -1762,6 +1701,7 @@ emit_line_number_info (MonoDwarfWriter *w, MonoMethod *method,
                }
 
                mono_debug_symfile_free_location (loc);
+               first = FALSE;
        }
 
        g_free (native_to_il_offset);
index 531b556e8c0442a9a7ac261fdafd9c5f2d5879e1..7badd246e8977d2b6598e4fb3ef550cd96897ad4 100644 (file)
@@ -343,6 +343,8 @@ mono_arch_get_restore_context (MonoTrampInfo **info, gboolean aot)
 
        /* load ESP into EBP */
        x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (MonoContext, esp), 4);
+       /* Align it, it can be unaligned if it was captured asynchronously */
+       x86_alu_reg_imm (code, X86_AND, X86_EBP, ~(MONO_ARCH_LOCALLOC_ALIGNMENT - 1));
        /* load return address into ECX */
        x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (MonoContext, eip), 4);
        /* save the return addr to the restored stack - 4 */
index 8ed2dbe2bf38f3f39537e92d90e0410525dd5c47..b0b95373fa7e279bcd127e38ced6db4dc5d284a1 100644 (file)
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Collections.ObjectModel;
 using System.Runtime.CompilerServices;
 using System.Threading.Tasks;
 
@@ -1428,7 +1429,8 @@ public class Tests
        [MethodImplAttribute (MethodImplOptions.NoInlining)]
        public static void call_async<T> (int i, int j) {
                Task<T> t = FooAsync<T> (1, 2);
-               t.RunSynchronously ();
+               // FIXME: This doesn't work
+               //t.RunSynchronously ();
        }
 
        // In AOT mode, the async infrastructure depends on gsharedvt methods
@@ -1436,6 +1438,12 @@ public class Tests
                call_async<string> (1, 2);
                return 0;
        }
+
+       public static int test_0_array_helper_gsharedvt () {
+               var arr = new AnEnum [16];
+               var c = new ReadOnlyCollection<AnEnum> (arr);
+               return c.Contains (AnEnum.Two) == false ? 0 : 1;
+       }
 }
 
 // #13191
index 73f31cc2ef7065a27d27dd51503b4e9b8b2fcfcf..6c0fcf1dc7936d5036235e880bb180c7dd54f66e 100644 (file)
                mono_cfg_set_exception (cfg, MONO_EXCEPTION_OUT_OF_MEMORY);             \
                goto exception_exit;    \
        } while (0)
+#define DISABLE_AOT(cfg) do { \
+               if ((cfg)->verbose_level >= 2)                                            \
+                       printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
+               (cfg)->disable_aot = TRUE;                                                        \
+       } while (0)
+
 /* Determine whenever 'ins' represents a load of the 'this' argument */
 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
 
@@ -1994,6 +2000,7 @@ ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharing
 
 handle_enum:
        type = mini_get_basic_type_from_generic (gsctx, type);
+       type = mini_replace_type (type);
        switch (type->type) {
        case MONO_TYPE_VOID:
                return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
@@ -3346,20 +3353,30 @@ get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgct
 
        g_assert (info);
 
-       for (i = 0; i < info->entries->len; ++i) {
-               MonoRuntimeGenericContextInfoTemplate *otemplate = g_ptr_array_index (info->entries, i);
+       for (i = 0; i < info->num_entries; ++i) {
+               MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
 
                if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
                        return i;
        }
 
-       template = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate));
+       if (info->num_entries == info->count_entries) {
+               MonoRuntimeGenericContextInfoTemplate *new_entries;
+               int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
+
+               new_entries = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
+
+               memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
+               info->entries = new_entries;
+               info->count_entries = new_count_entries;
+       }
+
+       idx = info->num_entries;
+       template = &info->entries [idx];
        template->info_type = rgctx_type;
        template->data = data;
 
-       idx = info->entries->len;
-
-       g_ptr_array_add (info->entries, template);
+       info->num_entries ++;
 
        return idx;
 }
@@ -4976,8 +4993,9 @@ emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst
 static MonoInst*
 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
 {
-       MonoInst *ins = NULL;
 #ifdef MONO_ARCH_SIMD_INTRINSICS
+       MonoInst *ins = NULL;
+
        if (cfg->opt & MONO_OPT_SIMD) {
                ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
                if (ins)
@@ -4985,7 +5003,7 @@ mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignat
        }
 #endif
 
-       return ins;
+       return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
 }
 
 static MonoInst*
@@ -5562,6 +5580,10 @@ mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign
        }
 #endif
 
+       ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
+       if (ins)
+               return ins;
+
        if (COMPILE_LLVM (cfg)) {
                ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
                if (ins)
@@ -6465,7 +6487,7 @@ is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmetho
        int i;
 
 #ifdef MONO_ARCH_HAVE_OP_TAIL_CALL
-       supported_tail_call = mono_arch_tail_call_supported (mono_method_signature (method), mono_method_signature (cmethod));
+       supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
 #else
        supported_tail_call = mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)) && !MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->ret);
 #endif
@@ -6963,8 +6985,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 
                info = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
                info->method = cfg->method;
-               // FIXME: Free this
-               info->entries = g_ptr_array_new ();
+               info->count_entries = 16;
+               info->entries = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
                cfg->gsharedvt_info = info;
 
                var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
@@ -7552,6 +7574,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                /* Handle tail calls similarly to calls */
                                n = fsig->param_count + fsig->hasthis;
 
+                               DISABLE_AOT (cfg);
+
                                MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
                                call->method = cmethod;
                                call->tail_call = TRUE;
@@ -10828,7 +10852,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                                                EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
                                                        } else {
                                                                /* FIXME: n is not a normal token */
-                                                               cfg->disable_aot = TRUE;
+                                                               DISABLE_AOT (cfg);
                                                                EMIT_NEW_PCONST (cfg, ins, NULL);
                                                        }
                                                } else {
@@ -11063,7 +11087,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                ip += 6;
                                inline_costs += 10 * num_calls++;
                                /* Can't embed random pointers into AOT code */
-                               cfg->disable_aot = 1;
+                               DISABLE_AOT (cfg);
                                break;
                        }
                        case CEE_MONO_JIT_ICALL_ADDR: {
@@ -11259,7 +11283,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                ins = mono_create_tls_get (cfg, key);
                                if (!ins) {
                                        if (cfg->compile_aot) {
-                                               cfg->disable_aot = TRUE;
+                                               DISABLE_AOT (cfg);
                                                MONO_INST_NEW (cfg, ins, OP_TLS_GET);
                                                ins->dreg = alloc_preg (cfg);
                                                ins->type = STACK_PTR;
@@ -12808,7 +12832,7 @@ mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
        }
 
        if (cfg->gsharedvt) {
-               gsharedvt_vreg_to_idx = g_new0 (int, cfg->next_vreg);
+               gsharedvt_vreg_to_idx = mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
 
                for (i = 0; i < cfg->num_varinfo; ++i) {
                        MonoInst *ins = cfg->varinfo [i];
index 53f39011d9812414944ef46c33b1261e60482fbc..434f74f3f6cfa29640989f7ffc3f0f2a6de0cdc4 100644 (file)
@@ -1204,7 +1204,7 @@ mono_arch_get_argument_info (MonoGenericSharingContext *gsctx, MonoMethodSignatu
 }
 
 gboolean
-mono_arch_tail_call_supported (MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
+mono_arch_tail_call_supported (MonoCompile *cfg, MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
 {
        CallInfo *c1, *c2;
        gboolean res;
index 9ced34a709f7c53d17af7c53693c176114ebb909..be941d97226c871d1238cf5899e0722fe9ecf241 100644 (file)
@@ -845,7 +845,7 @@ mono_arch_init (void)
        mono_aot_register_jit_icall ("mono_arm_throw_exception", mono_arm_throw_exception);
        mono_aot_register_jit_icall ("mono_arm_throw_exception_by_token", mono_arm_throw_exception_by_token);
        mono_aot_register_jit_icall ("mono_arm_resume_unwind", mono_arm_resume_unwind);
-#if defined(MONOTOUCH) || defined(MONO_EXTENSIONS)
+#if defined(MONO_GSHARING)
        mono_aot_register_jit_icall ("mono_arm_start_gsharedvt_call", mono_arm_start_gsharedvt_call);
 #endif
 
@@ -2508,17 +2508,24 @@ dyn_call_supported (CallInfo *cinfo, MonoMethodSignature *sig)
        }
 
        for (i = 0; i < cinfo->nargs; ++i) {
-               switch (cinfo->args [i].storage) {
+               ArgInfo *ainfo = &cinfo->args [i];
+               int last_slot;
+
+               switch (ainfo->storage) {
                case RegTypeGeneral:
                        break;
                case RegTypeIRegPair:
                        break;
                case RegTypeBase:
-                       if (cinfo->args [i].offset >= (DYN_CALL_STACK_ARGS * sizeof (gpointer)))
+                       if (ainfo->offset >= (DYN_CALL_STACK_ARGS * sizeof (gpointer)))
                                return FALSE;
                        break;
                case RegTypeStructByVal:
-                       if (cinfo->args [i].reg + cinfo->args [i].vtsize >= PARAM_REGS + DYN_CALL_STACK_ARGS)
+                       if (ainfo->size == 0)
+                               last_slot = PARAM_REGS + (ainfo->offset / 4) + ainfo->vtsize;
+                       else
+                               last_slot = ainfo->reg + ainfo->size + ainfo->vtsize;
+                       if (last_slot >= PARAM_REGS + DYN_CALL_STACK_ARGS)
                                return FALSE;
                        break;
                default:
@@ -5570,7 +5577,7 @@ mono_arch_emit_prolog (MonoCompile *cfg)
                                if (arm_is_imm12 (prev_sp_offset + ainfo->offset)) {
                                        ARM_LDR_IMM (code, inst->dreg, ARMREG_SP, (prev_sp_offset + ainfo->offset));
                                } else {
-                                       code = mono_arm_emit_load_imm (code, ARMREG_IP, inst->inst_offset);
+                                       code = mono_arm_emit_load_imm (code, ARMREG_IP, prev_sp_offset + ainfo->offset);
                                        ARM_LDR_REG_REG (code, inst->dreg, ARMREG_SP, ARMREG_IP);
                                }
                        } else
@@ -5622,11 +5629,21 @@ mono_arch_emit_prolog (MonoCompile *cfg)
                                        break;
                                }
                        } else if (ainfo->storage == RegTypeBaseGen) {
-                               g_assert (arm_is_imm12 (prev_sp_offset + ainfo->offset));
-                               g_assert (arm_is_imm12 (inst->inst_offset));
-                               ARM_LDR_IMM (code, ARMREG_LR, ARMREG_SP, (prev_sp_offset + ainfo->offset));
-                               ARM_STR_IMM (code, ARMREG_LR, inst->inst_basereg, inst->inst_offset + 4);
-                               ARM_STR_IMM (code, ARMREG_R3, inst->inst_basereg, inst->inst_offset);
+                               if (arm_is_imm12 (prev_sp_offset + ainfo->offset)) {
+                                       ARM_LDR_IMM (code, ARMREG_LR, ARMREG_SP, (prev_sp_offset + ainfo->offset));
+                               } else {
+                                       code = mono_arm_emit_load_imm (code, ARMREG_IP, prev_sp_offset + ainfo->offset);
+                                       ARM_LDR_REG_REG (code, ARMREG_LR, ARMREG_SP, ARMREG_IP);
+                               }
+                               if (arm_is_imm12 (inst->inst_offset + 4)) {
+                                       ARM_STR_IMM (code, ARMREG_LR, inst->inst_basereg, inst->inst_offset + 4);
+                                       ARM_STR_IMM (code, ARMREG_R3, inst->inst_basereg, inst->inst_offset);
+                               } else {
+                                       code = mono_arm_emit_load_imm (code, ARMREG_IP, inst->inst_offset + 4);
+                                       ARM_STR_REG_REG (code, ARMREG_LR, inst->inst_basereg, ARMREG_IP);
+                                       code = mono_arm_emit_load_imm (code, ARMREG_IP, inst->inst_offset);
+                                       ARM_STR_REG_REG (code, ARMREG_R3, inst->inst_basereg, ARMREG_IP);
+                               }
                        } else if (ainfo->storage == RegTypeBase || ainfo->storage == RegTypeGSharedVtOnStack) {
                                if (arm_is_imm12 (prev_sp_offset + ainfo->offset)) {
                                        ARM_LDR_IMM (code, ARMREG_LR, ARMREG_SP, (prev_sp_offset + ainfo->offset));
@@ -6847,7 +6864,7 @@ mono_arch_set_target (char *mtriple)
                eabi_supported = TRUE;
 }
 
-#if defined(MONOTOUCH) || defined(MONO_EXTENSIONS)
+#if defined(MONO_GSHARING)
 
 #include "../../../mono-extensions/mono/mini/mini-arm-gsharedvt.c"
 
index 9f566dd299a065c21152a65f8a192e4d7e01aec6..7050fab04c304ee6dd6777121661c6c87ab6f0cc 100644 (file)
@@ -297,12 +297,10 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoNativeThrea
        thread_state_t state;
        ucontext_t ctx;
        mcontext_t mctx;
-       guint32 domain_key, jit_key;
        MonoJitTlsData *jit_tls;
        void *domain;
-#if defined (MONO_ARCH_ENABLE_MONO_LMF_VAR)
-       guint32 lmf_key;
-#endif
+       MonoLMF *lmf;
+       MonoThreadInfo *info;
 
        /*Zero enough state to make sure the caller doesn't confuse itself*/
        tctx->valid = FALSE;
@@ -322,25 +320,40 @@ mono_thread_state_init_from_handle (MonoThreadUnwindState *tctx, MonoNativeThrea
 
        mono_sigctx_to_monoctx (&ctx, &tctx->ctx);
 
-       domain_key = mono_domain_get_tls_key ();
-       jit_key = mono_get_jit_tls_key ();
+       info = mono_thread_info_lookup (thread_id);
 
-       jit_tls = mono_mach_arch_get_tls_value_from_thread (thread_id, jit_key);
-       domain = mono_mach_arch_get_tls_value_from_thread (thread_id, domain_key);
+       if (info) {
+               /* mono_set_jit_tls () sets this */
+               jit_tls = mono_thread_info_tls_get (info, TLS_KEY_JIT_TLS);
+               /* SET_APPDOMAIN () sets this */
+               domain = mono_thread_info_tls_get (info, TLS_KEY_DOMAIN);
+       } else {
+               jit_tls = NULL;
+               domain = NULL;
+       }
 
        /*Thread already started to cleanup, can no longer capture unwind state*/
        if (!jit_tls || !domain)
                return FALSE;
 
-#if defined (MONO_ARCH_ENABLE_MONO_LMF_VAR)
-       lmf_key =  mono_get_lmf_tls_offset ();
-       tctx->unwind_data [MONO_UNWIND_DATA_LMF] = mono_mach_arch_get_tls_value_from_thread (thread_id, lmf_key);;
-#else
-       tctx->unwind_data [MONO_UNWIND_DATA_LMF] = jit_tls ? jit_tls->lmf : NULL;
-#endif
+       /*
+        * The current LMF address is kept in a separate TLS variable, and its hard to read its value without
+        * arch-specific code. But the address of the TLS variable is stored in another TLS variable which
+        * can be accessed through MonoThreadInfo.
+        */
+       lmf = NULL;
+       if (info) {
+               gpointer *addr;
+
+               /* mono_set_lmf_addr () sets this */
+               addr = mono_thread_info_tls_get (info, TLS_KEY_LMF_ADDR);
+               if (addr)
+                       lmf = *addr;
+       }
 
        tctx->unwind_data [MONO_UNWIND_DATA_DOMAIN] = domain;
        tctx->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
+       tctx->unwind_data [MONO_UNWIND_DATA_LMF] = lmf;
        tctx->valid = TRUE;
 
        return TRUE;
index fcdb5405990a20023dd6415ef61cfafbe0efc9fe..3dba78bd2b79c8fdb2b29922016c742cfd8d7d66 100644 (file)
@@ -1933,7 +1933,7 @@ mono_setup_altstack (MonoJitTlsData *tls)
        if (mono_running_on_valgrind ())
                return;
 
-       mono_thread_get_stack_bounds (&staddr, &stsize);
+       mono_thread_info_get_stack_bounds (&staddr, &stsize);
 
        g_assert (staddr);
 
index ac7d9ea2c7eea5518500393c5483fa749a0195d5..12a6bb6e60937f8453bfcf296417836437f1f9bb 100644 (file)
@@ -572,26 +572,26 @@ inflate_info (MonoRuntimeGenericContextInfoTemplate *oti, MonoGenericContext *co
                return inflated_method;
        }
        case MONO_RGCTX_INFO_METHOD_GSHAREDVT_INFO: {
-               MonoGSharedVtMethodInfo *info = data;
+               MonoGSharedVtMethodInfo *oinfo = data;
                MonoGSharedVtMethodInfo *res;
+               MonoDomain *domain = mono_domain_get ();
                int i;
 
-               // FIXME:
-               res = g_new0 (MonoGSharedVtMethodInfo, 1);
+               res = mono_domain_alloc0 (domain, sizeof (MonoGSharedVtMethodInfo));
                /*
                res->nlocals = info->nlocals;
                res->locals_types = g_new0 (MonoType*, info->nlocals);
                for (i = 0; i < info->nlocals; ++i)
                        res->locals_types [i] = mono_class_inflate_generic_type (info->locals_types [i], context);
                */
-               res->entries = g_ptr_array_new ();
-               for (i = 0; i < info->entries->len; ++i) {
-                       MonoRuntimeGenericContextInfoTemplate *otemplate = g_ptr_array_index (info->entries, i);
-                       MonoRuntimeGenericContextInfoTemplate *template = g_new0 (MonoRuntimeGenericContextInfoTemplate, 1);
+               res->num_entries = oinfo->num_entries;
+               res->entries = mono_domain_alloc0 (domain, sizeof (MonoRuntimeGenericContextInfoTemplate) * oinfo->num_entries);
+               for (i = 0; i < oinfo->num_entries; ++i) {
+                       MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
+                       MonoRuntimeGenericContextInfoTemplate *template = &res->entries [i];
 
                        memcpy (template, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
                        template->data = inflate_info (template, context, class, FALSE);
-                       g_ptr_array_add (res->entries, template);
                }
                return res;
        }
@@ -603,9 +603,9 @@ inflate_info (MonoRuntimeGenericContextInfoTemplate *oti, MonoGenericContext *co
                MonoType *inflated_type = mono_class_inflate_generic_type (&method->klass->byval_arg, context);
                MonoClass *inflated_class = mono_class_from_mono_type (inflated_type);
                MonoJumpInfoGSharedVtCall *res;
+               MonoDomain *domain = mono_domain_get ();
 
-               // FIXME:
-               res = g_new0 (MonoJumpInfoGSharedVtCall, 1);
+               res = mono_domain_alloc0 (domain, sizeof (MonoJumpInfoGSharedVtCall));
                /* Keep the original signature */
                res->sig = info->sig;
 
@@ -1054,7 +1054,7 @@ class_type_info (MonoDomain *domain, MonoClass *class, MonoRgctxInfoType info_ty
                        sig = mono_method_signature (method);
                        gsig = mono_method_signature (gmethod);
                        ctx = mono_method_get_context (gmethod);
-                       mini_init_gsctx (ctx, &gsctx);
+                       mini_init_gsctx (NULL, NULL, ctx, &gsctx);
 
                        addr = mini_get_gsharedvt_wrapper (FALSE, addr, sig, gsig, &gsctx, -1, FALSE);
                        addr = mono_create_static_rgctx_trampoline (method, addr);
@@ -1446,11 +1446,11 @@ instantiate_info (MonoDomain *domain, MonoRuntimeGenericContextInfoTemplate *oti
                int i, offset, align, size;
 
                // FIXME:
-               res = g_malloc0 (sizeof (MonoGSharedVtMethodRuntimeInfo) + (info->entries->len * sizeof (gpointer)));
+               res = g_malloc0 (sizeof (MonoGSharedVtMethodRuntimeInfo) + (info->num_entries * sizeof (gpointer)));
 
                offset = 0;
-               for (i = 0; i < info->entries->len; ++i) {
-                       MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
+               for (i = 0; i < info->num_entries; ++i) {
+                       MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
 
                        switch (template->info_type) {
                        case MONO_RGCTX_INFO_LOCAL_OFFSET:
@@ -2550,6 +2550,8 @@ mini_get_basic_type_from_generic (MonoGenericSharingContext *gsctx, MonoType *ty
 MonoType*
 mini_type_get_underlying_type (MonoGenericSharingContext *gsctx, MonoType *type)
 {
+       type = mini_native_type_replace_type (type);
+
        if (type->byref)
                return &mono_defaults.int_class->byval_arg;
        if (!type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR) && mini_is_gsharedvt_type_gsctx (gsctx, type))
@@ -2706,7 +2708,7 @@ mini_is_gsharedvt_variable_klass (MonoCompile *cfg, MonoClass *klass)
        return mini_is_gsharedvt_variable_type (cfg, &klass->byval_arg);
 }
 
-#if defined(MONOTOUCH) || defined(MONO_EXTENSIONS)
+#if defined(MONO_GSHARING)
 
 #include "../../../mono-extensions/mono/mini/mini-generic-sharing-gsharedvt.c"
 
diff --git a/mono/mini/mini-native-types.c b/mono/mini/mini-native-types.c
new file mode 100644 (file)
index 0000000..9dadbc3
--- /dev/null
@@ -0,0 +1,23 @@
+#include <config.h>
+
+#if defined(MONO_NATIVE_TYPES)
+
+#include "../../../mono-extensions/mono/mini/mini-native-types.c"
+
+#else
+
+#include "mini.h"
+
+MonoType*
+mini_native_type_replace_type (MonoType *type)
+{
+       return type;
+}
+
+MonoInst*
+mono_emit_native_types_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
+{
+       return NULL;
+}
+
+#endif
index 34dd19f59abc0be2435c035cfac8f65a8c40693e..69a1d3d78aa16d9558fff6e6d915d9a95f816ec0 100644 (file)
@@ -1254,7 +1254,7 @@ get_call_info (MonoGenericSharingContext *gsctx, MonoMethodSignature *sig)
 }
 
 gboolean
-mono_arch_tail_call_supported (MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
+mono_arch_tail_call_supported (MonoCompile *cfg, MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
 {
        CallInfo *c1, *c2;
        gboolean res;
index 3cdfbe9b66bbe74b69926d92531db0a9b2f4e028..80f5dc3bdee113eb059a19f41e64d74f4c52af69 100644 (file)
@@ -206,10 +206,7 @@ __attribute__ ((noinline))
                        WrapperInfo *info = mono_marshal_get_wrapper_info (impl);
 
                        if (info && info->subtype == WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER) {
-                               // FIXME: This needs a gsharedvt-out trampoline, since the caller uses the gsharedvt calling conv, but the
-                               // wrapper is a normal non-generic method.
                                *need_rgctx_tramp = TRUE;
-                               //g_assert_not_reached ();
                        }
                }
 
@@ -290,10 +287,10 @@ mini_add_method_trampoline (MonoMethod *orig_method, MonoMethod *m, gpointer com
        gpointer addr = compiled_method;
        gboolean callee_gsharedvt, callee_array_helper;
        MonoMethod *jmethod = NULL;
-       MonoJitInfo *ji = 
-               mini_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (compiled_method), NULL);
+       MonoJitInfo *ji;
 
-       // FIXME: This loads information from AOT
+       // FIXME: This loads information from AOT (perf problem)
+       ji = mini_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (compiled_method), NULL);
        callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
 
        callee_array_helper = FALSE;
@@ -357,7 +354,17 @@ mini_add_method_trampoline (MonoMethod *orig_method, MonoMethod *m, gpointer com
                //printf ("IN: %s\n", mono_method_full_name (m, TRUE));
        }
 
-       if (add_static_rgctx_tramp && !callee_array_helper)
+       if (callee_array_helper) {
+               add_static_rgctx_tramp = FALSE;
+               /* FIXME: ji->from_aot is not set for llvm methods */
+               if (ji && (ji->from_aot || mono_aot_only)) {
+                       /* In AOT mode, compiled_method points to one of the InternalArray methods in Array. */
+                       if (mono_method_needs_static_rgctx_invoke (jinfo_get_method (ji), TRUE))
+                               add_static_rgctx_tramp = TRUE;
+               }
+       }
+
+       if (add_static_rgctx_tramp)
                addr = mono_create_static_rgctx_trampoline (m, addr);
 
        return addr;
@@ -1116,13 +1123,8 @@ mono_handler_block_guard_trampoline (mgreg_t *regs, guint8 *code, gpointer *tram
                exc = mono_thread_resume_interruption ();
 
        if (exc) {
-               static void (*restore_context) (MonoContext *);
-
-               if (!restore_context)
-                       restore_context = mono_get_restore_context ();
-
                mono_handle_exception (&ctx, exc);
-               restore_context (&ctx);
+               mono_restore_context (&ctx);
        }
 
        return resume_ip;
index a8641f7cddb379473011af739a52b7c4ef26d5ca..6b6ba7ad2f94fb6989412733dfd1a098e2fd5e82 100644 (file)
@@ -158,6 +158,6 @@ mono_unwind_decode_llvm_mono_fde (guint8 *fde, int fde_len, guint8 *cie, guint8
 
 GSList* mono_unwind_get_cie_program (void) MONO_INTERNAL;
 
-void mono_print_unwind_info (guint8 *unwind_info, int unwind_info_len) MONO_INTERNAL;
+void mono_print_unwind_info (guint8 *unwind_info, int unwind_info_len) MONO_LLVM_INTERNAL;
 
 #endif
index d008fc2008df7bedf1efb2a843a1923fac725cfd..83d7de2debc380df2b1a14fa4ed3dbc70bf9741c 100755 (executable)
@@ -701,12 +701,16 @@ mono_arch_get_argument_info (MonoGenericSharingContext *gsctx, MonoMethodSignatu
 }
 
 gboolean
-mono_arch_tail_call_supported (MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
+mono_arch_tail_call_supported (MonoCompile *cfg, MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
 {
        MonoType *callee_ret;
        CallInfo *c1, *c2;
        gboolean res;
 
+       if (cfg->compile_aot && !cfg->full_aot)
+               /* OP_TAILCALL doesn't work with AOT */
+               return FALSE;
+
        c1 = get_call_info (NULL, NULL, caller_sig);
        c2 = get_call_info (NULL, NULL, callee_sig);
        /*
@@ -759,7 +763,7 @@ mono_arch_init (void)
 
        mono_aot_register_jit_icall ("mono_x86_throw_exception", mono_x86_throw_exception);
        mono_aot_register_jit_icall ("mono_x86_throw_corlib_exception", mono_x86_throw_corlib_exception);
-#if defined(MONOTOUCH) || defined(MONO_EXTENSIONS)
+#if defined(MONO_GSHARING)
        mono_aot_register_jit_icall ("mono_x86_start_gsharedvt_call", mono_x86_start_gsharedvt_call);
 #endif
 }
@@ -6850,7 +6854,7 @@ mono_arch_init_lmf_ext (MonoLMFExt *ext, gpointer prev_lmf)
 
 #endif
 
-#if defined(MONOTOUCH) || defined(MONO_EXTENSIONS)
+#if defined(MONO_GSHARING)
 
 #include "../../../mono-extensions/mono/mini/mini-x86-gsharedvt.c"
 
index 631233ebcfb89609dccbbd2bee31aecd3d8fb998..23e4117fd34102abd314e51205d36f6e4e26fe51 100644 (file)
@@ -60,6 +60,7 @@
 #include <mono/utils/mono-hwcap.h>
 #include <mono/utils/dtrace.h>
 #include <mono/utils/mono-signal-handler.h>
+#include <mono/utils/mono-threads.h>
 
 #include "mini.h"
 #include "mini-llvm.h"
@@ -670,9 +671,9 @@ mono_tramp_info_register (MonoTrampInfo *info)
        copy->code_size = info->code_size;
        copy->name = g_strdup (info->name);
 
-       mono_loader_lock_if_inited ();
+       mono_jit_lock ();
        tramp_infos = g_slist_prepend (tramp_infos, copy);
-       mono_loader_unlock_if_inited ();
+       mono_jit_unlock ();
 
        mono_save_trampoline_xdebug_info (info);
 
@@ -2703,22 +2704,42 @@ mono_set_lmf (MonoLMF *lmf)
        (*mono_get_lmf_addr ()) = lmf;
 }
 
+MonoJitTlsData*
+mono_get_jit_tls (void)
+{
+       return mono_native_tls_get_value (mono_jit_tls_id);
+}
+
 static void
 mono_set_jit_tls (MonoJitTlsData *jit_tls)
 {
+       MonoThreadInfo *info;
+
        mono_native_tls_set_value (mono_jit_tls_id, jit_tls);
 
 #ifdef MONO_HAVE_FAST_TLS
        MONO_FAST_TLS_SET (mono_jit_tls, jit_tls);
 #endif
+
+       /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
+       info = mono_thread_info_current ();
+       if (info)
+               mono_thread_info_tls_set (info, TLS_KEY_JIT_TLS, jit_tls);
 }
 
 static void
 mono_set_lmf_addr (gpointer lmf_addr)
 {
+       MonoThreadInfo *info;
+
 #ifdef MONO_HAVE_FAST_TLS
        MONO_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
 #endif
+
+       /* Save it into MonoThreadInfo so it can be accessed by mono_thread_state_init_from_handle () */
+       info = mono_thread_info_current ();
+       if (info)
+               mono_thread_info_tls_set (info, TLS_KEY_LMF_ADDR, lmf_addr);
 }
 
 /*
@@ -3117,15 +3138,12 @@ mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
                info = mono_mempool_alloc (mp, sizeof (MonoGSharedVtMethodInfo));
                res->data.gsharedvt_method = info;
                memcpy (info, oinfo, sizeof (MonoGSharedVtMethodInfo));
-               info->entries = g_ptr_array_new ();
-               if (oinfo->entries) {
-                       for (i = 0; i < oinfo->entries->len; ++i) {
-                               MonoRuntimeGenericContextInfoTemplate *otemplate = g_ptr_array_index (oinfo->entries, i);
-                               MonoRuntimeGenericContextInfoTemplate *template = mono_mempool_alloc0 (mp, sizeof (MonoRuntimeGenericContextInfoTemplate));
+               info->entries = mono_mempool_alloc (mp, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
+               for (i = 0; i < oinfo->num_entries; ++i) {
+                       MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
+                       MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
 
-                               memcpy (template, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
-                               g_ptr_array_add (info->entries, template);
-                       }
+                       memcpy (template, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
                }
                //info->locals_types = mono_mempool_alloc0 (mp, info->nlocals * sizeof (MonoType*));
                //memcpy (info->locals_types, oinfo->locals_types, info->nlocals * sizeof (MonoType*));
@@ -3564,13 +3582,13 @@ mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code,
                        /* Make a copy into the domain mempool */
                        info = g_malloc0 (sizeof (MonoGSharedVtMethodInfo)); //mono_domain_alloc0 (domain, sizeof (MonoGSharedVtMethodInfo));
                        info->method = oinfo->method;
-                       info->entries = g_ptr_array_new ();
-                       for (i = 0; i < oinfo->entries->len; ++i) {
-                               MonoRuntimeGenericContextInfoTemplate *otemplate = g_ptr_array_index (oinfo->entries, i);
-                               MonoRuntimeGenericContextInfoTemplate *template = g_malloc0 (sizeof (MonoRuntimeGenericContextInfoTemplate));
+                       info->num_entries = oinfo->num_entries;
+                       info->entries = g_malloc0 (sizeof (MonoRuntimeGenericContextInfoTemplate) * info->num_entries);
+                       for (i = 0; i < oinfo->num_entries; ++i) {
+                               MonoRuntimeGenericContextInfoTemplate *otemplate = &oinfo->entries [i];
+                               MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
 
                                memcpy (template, otemplate, sizeof (MonoRuntimeGenericContextInfoTemplate));
-                               g_ptr_array_add (info->entries, template);
                        }
                        slot = mono_method_lookup_or_register_info (entry->method, entry->in_mrgctx, info, entry->info_type, mono_method_get_context (entry->method));
                        break;
@@ -4261,6 +4279,9 @@ create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info)
        jinfo->code_size = info->code_size;
        jinfo->used_regs = mono_cache_unwind_info (uw_info, info_len);
 
+       if (!info->uw_info)
+               g_free (uw_info);
+
        return jinfo;
 }
 
@@ -4360,7 +4381,7 @@ create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
                        gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
                else
                        gi->generic_sharing_context = mono_domain_alloc0 (cfg->domain, sizeof (MonoGenericSharingContext));
-               memcpy (gi->generic_sharing_context, cfg->generic_sharing_context, sizeof (MonoGenericSharingContext));
+               mini_init_gsctx (cfg->method->dynamic ? NULL : cfg->domain, NULL, cfg->gsctx_context, gi->generic_sharing_context);
 
                if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
                                mini_method_get_context (method_to_compile)->method_inst ||
@@ -4786,16 +4807,21 @@ mini_get_shared_method (MonoMethod *method)
 }
 
 void
-mini_init_gsctx (MonoGenericContext *context, MonoGenericSharingContext *gsctx)
+mini_init_gsctx (MonoDomain *domain, MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx)
 {
        MonoGenericInst *inst;
        int i;
 
        memset (gsctx, 0, sizeof (MonoGenericSharingContext));
 
-       if (context->class_inst) {
+       if (context && context->class_inst) {
                inst = context->class_inst;
-               gsctx->var_is_vt = g_new0 (gboolean, inst->type_argc);
+               if (domain)
+                       gsctx->var_is_vt = mono_domain_alloc0 (domain, sizeof (gboolean) * inst->type_argc);
+               else if (mp)
+                       gsctx->var_is_vt = mono_mempool_alloc0 (mp, sizeof (gboolean) * inst->type_argc);
+               else
+                       gsctx->var_is_vt = g_new0 (gboolean, inst->type_argc);
 
                for (i = 0; i < inst->type_argc; ++i) {
                        MonoType *type = inst->type_argv [i];
@@ -4804,9 +4830,14 @@ mini_init_gsctx (MonoGenericContext *context, MonoGenericSharingContext *gsctx)
                                gsctx->var_is_vt [i] = TRUE;
                }
        }
-       if (context->method_inst) {
+       if (context && context->method_inst) {
                inst = context->method_inst;
-               gsctx->mvar_is_vt = g_new0 (gboolean, inst->type_argc);
+               if (domain)
+                       gsctx->mvar_is_vt = mono_domain_alloc0 (domain, sizeof (gboolean) * inst->type_argc);
+               else if (mp)
+                       gsctx->mvar_is_vt = mono_mempool_alloc0 (mp, sizeof (gboolean) * inst->type_argc);
+               else
+                       gsctx->mvar_is_vt = g_new0 (gboolean, inst->type_argc);
 
                for (i = 0; i < inst->type_argc; ++i) {
                        MonoType *type = inst->type_argv [i];
@@ -4823,15 +4854,14 @@ mini_init_gsctx (MonoGenericContext *context, MonoGenericSharingContext *gsctx)
  * @method: the method to compile
  * @opts: the optimization flags to use
  * @domain: the domain where the method will be compiled in
- * @run_cctors: whether we should run type ctors if possible
- * @compile_aot: whether this is an AOT compilation
+ * @flags: compilation flags
  * @parts: debug flag
  *
  * Returns: a MonoCompile* pointer. Caller must check the exception_type
  * field in the returned struct to see if compilation succeded.
  */
 MonoCompile*
-mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
+mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts)
 {
        MonoMethodHeader *header;
        MonoMethodSignature *sig;
@@ -4843,6 +4873,9 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
        gboolean try_generic_shared, try_llvm = FALSE;
        MonoMethod *method_to_compile, *method_to_register;
        gboolean method_is_gshared = FALSE;
+       gboolean run_cctors = (flags & JIT_FLAG_RUN_CCTORS) ? 1 : 0;
+       gboolean compile_aot = (flags & JIT_FLAG_AOT) ? 1 : 0;
+       gboolean full_aot = (flags & JIT_FLAG_FULL_AOT) ? 1 : 0;
 
        InterlockedIncrement (&mono_jit_stats.methods_compiled);
        if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
@@ -4909,6 +4942,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
        cfg->domain = domain;
        cfg->verbose_level = mini_verbose;
        cfg->compile_aot = compile_aot;
+       cfg->full_aot = full_aot;
        cfg->skip_visibility = method->skip_visibility;
        cfg->orig_method = method;
        cfg->gen_seq_points = debug_options.gen_seq_points;
@@ -4931,7 +4965,6 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
                MonoMethodInflated *inflated;
                MonoGenericContext *context;
 
-               // FIXME: Free the contents of gsctx if compilation fails
                if (method_is_gshared) {
                        g_assert (method->is_inflated);
                        inflated = (MonoMethodInflated*)method;
@@ -4945,7 +4978,8 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
                        context = &inflated->context;
                }
 
-               mini_init_gsctx (context, &cfg->gsctx);
+               mini_init_gsctx (NULL, cfg->mempool, context, &cfg->gsctx);
+               cfg->gsctx_context = context;
 
                cfg->gsharedvt = TRUE;
                // FIXME:
@@ -5689,7 +5723,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
 #else
 
 MonoCompile*
-mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
+mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts)
 {
        g_assert_not_reached ();
        return NULL;
@@ -5934,7 +5968,7 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in
 
        jit_timer = g_timer_new ();
 
-       cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
+       cfg = mini_method_compile (method, opt, target_domain, JIT_FLAG_RUN_CCTORS, 0);
        prof_method = cfg->method;
 
        g_timer_stop (jit_timer);
@@ -7016,6 +7050,13 @@ delete_jump_list (gpointer key, gpointer value, gpointer user_data)
        g_slist_free (jlist->list);
 }
 
+static void
+delete_got_slot_list (gpointer key, gpointer value, gpointer user_data)
+{
+       GSList *list = value;
+       g_slist_free (list);
+}
+
 static void
 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
 {
@@ -7057,7 +7098,7 @@ mini_free_jit_domain_info (MonoDomain *domain)
        g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
        g_hash_table_destroy (info->jump_target_hash);
        if (info->jump_target_got_slot_hash) {
-               g_hash_table_foreach (info->jump_target_got_slot_hash, delete_jump_list, NULL);
+               g_hash_table_foreach (info->jump_target_got_slot_hash, delete_got_slot_list, NULL);
                g_hash_table_destroy (info->jump_target_got_slot_hash);
        }
        if (info->dynamic_code_hash) {
@@ -7101,6 +7142,8 @@ mini_init (const char *filename, const char *runtime_version)
        }
 #endif
 
+       InitializeCriticalSection (&jit_mutex);
+
        /* Happens when using the embedding interface */
        if (!default_opt_set)
                default_opt = mono_parse_default_optimizations (NULL);
@@ -7110,8 +7153,6 @@ mini_init (const char *filename, const char *runtime_version)
                mono_set_generic_sharing_vt_supported (TRUE);
 #endif
 
-       InitializeCriticalSection (&jit_mutex);
-
 #ifdef MONO_HAVE_FAST_TLS
        MONO_FAST_TLS_INIT (mono_jit_tls);
        MONO_FAST_TLS_INIT (mono_lmf_addr);
@@ -7838,7 +7879,7 @@ mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot)
 
 #endif
 
-#if defined(MONO_ARCH_GSHAREDVT_SUPPORTED) && !defined(MONOTOUCH) && !defined(MONO_EXTENSIONS)
+#if defined(MONO_ARCH_GSHAREDVT_SUPPORTED) && !defined(MONO_GSHARING)
 
 gboolean
 mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig)
@@ -7958,5 +7999,6 @@ mono_jumptable_get_entry (guint8 *code_ptr)
 MonoType*
 mini_replace_type (MonoType *type)
 {
-       return mono_type_get_underlying_type (type);
+       type = mono_type_get_underlying_type (type);
+       return mini_native_type_replace_type (type);
 }
index dab040782d0b9d47f4a021f7fe1757de1f1c18c0..d61f7c93b7c183544ed9c0db71b27513f93ce612 100644 (file)
@@ -1132,8 +1132,8 @@ typedef struct {
 
 typedef struct {
        MonoMethod *method;
-       /* Array of MonoRuntimeGenericContextInfoTemplate* entries */
-       GPtrArray *entries;
+       MonoRuntimeGenericContextInfoTemplate *entries;
+       int num_entries, count_entries;
 } MonoGSharedVtMethodInfo;
 
 /* This is used by gsharedvt methods to allocate locals and compute local offsets */
@@ -1274,6 +1274,16 @@ enum {
        MONO_OPT_LAST
 };
 
+/* Flags for mini_method_compile () */
+typedef enum {
+       /* Whenever to run cctors during JITting */
+       JIT_FLAG_RUN_CCTORS = (1 << 0),
+       /* Whenever this is an AOT compilation */
+       JIT_FLAG_AOT = (1 << 1),
+       /* Whenever this is a full AOT compilation */
+       JIT_FLAG_FULL_AOT = (1 << 2)
+} JitFlags;
+
 /* Bit-fields in the MonoBasicBlock.region */
 #define MONO_REGION_TRY       0
 #define MONO_REGION_FINALLY  16
@@ -1372,6 +1382,7 @@ typedef struct {
        MonoGenericSharingContext *generic_sharing_context;
 
        MonoGenericSharingContext gsctx;
+       MonoGenericContext *gsctx_context;
 
        gboolean gsharedvt;
 
@@ -1420,6 +1431,7 @@ typedef struct {
        guint            run_cctors : 1;
        guint            need_lmf_area : 1;
        guint            compile_aot : 1;
+       guint            full_aot : 1;
        guint            compile_llvm : 1;
        guint            got_var_allocated : 1;
        guint            ret_var_is_local : 1;
@@ -1985,6 +1997,7 @@ gpointer  mono_jit_compile_method           (MonoMethod *method) MONO_INTERNAL;
 MonoLMF * mono_get_lmf                      (void) MONO_INTERNAL;
 MonoLMF** mono_get_lmf_addr                 (void) MONO_INTERNAL;
 void      mono_set_lmf                      (MonoLMF *lmf) MONO_INTERNAL;
+MonoJitTlsData* mono_get_jit_tls            (void) MONO_INTERNAL;
 MONO_API MonoDomain *mono_jit_thread_attach          (MonoDomain *domain);
 MONO_API void      mono_jit_set_domain               (MonoDomain *domain);
 MonoNativeTlsKey mono_get_jit_tls_key       (void) MONO_INTERNAL;
@@ -2007,7 +2020,7 @@ void      mono_linear_scan                  (MonoCompile *cfg, GList *vars, GLis
 void      mono_global_regalloc              (MonoCompile *cfg) MONO_INTERNAL;
 void      mono_create_jump_table            (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks) MONO_INTERNAL;
 int       mono_compile_assembly             (MonoAssembly *ass, guint32 opts, const char *aot_options) MONO_INTERNAL;
-MonoCompile *mini_method_compile            (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts) MONO_INTERNAL;
+MonoCompile *mini_method_compile            (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts) MONO_INTERNAL;
 void      mono_destroy_compile              (MonoCompile *cfg) MONO_INTERNAL;
 MonoJitICallInfo *mono_find_jit_opcode_emulation (int opcode) MONO_INTERNAL;
 void     mono_print_ins_index (int i, MonoInst *ins) MONO_INTERNAL;
@@ -2300,7 +2313,7 @@ gboolean  mono_arch_gsharedvt_sig_supported     (MonoMethodSignature *sig) MONO_
 gpointer  mono_arch_get_gsharedvt_trampoline    (MonoTrampInfo **info, gboolean aot) MONO_INTERNAL;
 gpointer  mono_arch_get_gsharedvt_call_info     (gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, MonoGenericSharingContext *gsctx, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli) MONO_INTERNAL;
 gboolean  mono_arch_opcode_needs_emulation      (MonoCompile *cfg, int opcode) MONO_INTERNAL;
-gboolean  mono_arch_tail_call_supported         (MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig) MONO_INTERNAL;
+gboolean  mono_arch_tail_call_supported         (MonoCompile *cfg, MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig) MONO_INTERNAL;
 int       mono_arch_translate_tls_offset        (int offset) MONO_INTERNAL;
 
 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
@@ -2641,13 +2654,13 @@ gboolean mini_is_gsharedvt_klass (MonoCompile *cfg, MonoClass *klass); /* should
 gboolean mini_is_gsharedvt_type (MonoCompile *cfg, MonoType *t) MONO_INTERNAL;
 gboolean mini_is_gsharedvt_signature (MonoCompile *cfg, MonoMethodSignature *sig) MONO_INTERNAL;
 gboolean mini_is_gsharedvt_type_gsctx (MonoGenericSharingContext *gsctx, MonoType *t) MONO_INTERNAL;
-gboolean mini_is_gsharedvt_variable_type (MonoCompile *cfg, MonoType *t) MONO_INTERNAL;
-gboolean mini_is_gsharedvt_variable_klass (MonoCompile *cfg, MonoClass *klass) MONO_INTERNAL;
+gboolean mini_is_gsharedvt_variable_type (MonoCompile *cfg, MonoType *t) MONO_LLVM_INTERNAL;
+gboolean mini_is_gsharedvt_variable_klass (MonoCompile *cfg, MonoClass *klass) MONO_LLVM_INTERNAL;
 gboolean mini_is_gsharedvt_sharable_method (MonoMethod *method) MONO_INTERNAL;
 gboolean mini_is_gsharedvt_variable_signature (MonoMethodSignature *sig) MONO_INTERNAL;
 gboolean mini_is_gsharedvt_sharable_inst (MonoGenericInst *inst) MONO_INTERNAL;
 gpointer mini_method_get_rgctx (MonoMethod *m) MONO_INTERNAL;
-void mini_init_gsctx (MonoGenericContext *context, MonoGenericSharingContext *gsctx) MONO_INTERNAL;
+void mini_init_gsctx (MonoDomain *domain, MonoMemPool *mp, MonoGenericContext *context, MonoGenericSharingContext *gsctx) MONO_INTERNAL;
 
 gpointer mini_get_gsharedvt_wrapper (gboolean gsharedvt_in, gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, MonoGenericSharingContext *gsctx,
                                                                         gint32 vcall_offset, gboolean calli) MONO_INTERNAL;
@@ -2709,6 +2722,9 @@ MonoInst*   mono_emit_simd_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, Mo
 guint32     mono_arch_cpu_enumerate_simd_versions (void) MONO_INTERNAL;
 void        mono_simd_intrinsics_init (void) MONO_INTERNAL;
 
+MonoInst*   mono_emit_native_types_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args) MONO_INTERNAL;
+MonoType*   mini_native_type_replace_type (MonoType *type) MONO_INTERNAL;
+
 #ifdef __linux__
 /* maybe enable also for other systems? */
 #define ENABLE_JIT_MAP 1
index 551b2a2fdaf61777910edb599686a6abacf8cfd7..cbc3b3b2b4ce49ddee7b78298841e7f97c009f5b 100644 (file)
 #  define fprintf(__ignore, ...) g_log ("mono-gc", G_LOG_LEVEL_MESSAGE, __VA_ARGS__)
 #endif
 
-#define RETURN_ADDRESS(N) (__builtin_extract_return_addr (__builtin_return_address (N)))
+#ifdef __GNUC__
+
+#define RETURN_ADDRESS_N(N) (__builtin_extract_return_addr (__builtin_return_address (N)))
+#define RETURN_ADDRESS() RETURN_ADDRESS_N(0)
+
+#elif defined(_MSC_VER)
+
+#include <intrin.h>
+#pragma intrinsic(_ReturnAddress)
+
+#define RETURN_ADDRESS() _ReturnAddress()
+#define RETURN_ADDRESS_N(N) NULL
+
+#else
+
+#error "Missing return address intrinsics implementation"
+
+#endif
 
 static MonoTraceSpec trace_spec;
 
@@ -403,7 +420,7 @@ mono_trace_enter_method (MonoMethod *method, char *ebp)
        g_free (fname);
 
        if (!ebp) {
-               printf (") ip: %p\n", RETURN_ADDRESS (1));
+               printf (") ip: %p\n", RETURN_ADDRESS_N (1));
                return;
        }       
 
@@ -413,7 +430,7 @@ mono_trace_enter_method (MonoMethod *method, char *ebp)
 
        if (method->is_inflated) {
                /* FIXME: Might be better to pass the ji itself */
-               MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), RETURN_ADDRESS (0), NULL);
+               MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), RETURN_ADDRESS (), NULL);
                if (ji) {
                        gsctx = mono_jit_info_get_generic_sharing_context (ji);
                        if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
@@ -571,7 +588,7 @@ mono_trace_leave_method (MonoMethod *method, ...)
 
        if (method->is_inflated) {
                /* FIXME: Might be better to pass the ji itself */
-               MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), RETURN_ADDRESS (0), NULL);
+               MonoJitInfo *ji = mini_jit_info_table_find (mono_domain_get (), RETURN_ADDRESS (), NULL);
                if (ji) {
                        gsctx = mono_jit_info_get_generic_sharing_context (ji);
                        if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
@@ -684,7 +701,7 @@ handle_enum:
                printf ("(unknown return type %x)", mono_method_signature (method)->ret->type);
        }
 
-       //printf (" ip: %p\n", RETURN_ADDRESS (1));
+       //printf (" ip: %p\n", RETURN_ADDRESS_N (1));
        printf ("\n");
        fflush (stdout);
 }
index 6e973e0e7424f90d2a4a44ceac65b6d78b4bdca9..b2a8ef7cf7ea61346905248edbb68dc8937b1a51 100644 (file)
@@ -1077,7 +1077,7 @@ mono_arch_get_gsharedvt_arg_trampoline (MonoDomain *domain, gpointer arg, gpoint
 
 #endif
 
-#if defined(MONOTOUCH) || defined(MONO_EXTENSIONS)
+#if defined(MONO_GSHARING)
 
 #include "../../../mono-extensions/mono/mini/tramp-arm-gsharedvt.c"
 
index 4e42d0d88f7460568d44228ca83b3ab91595d566..6d9a6683d313ff19cd4cb5cff6d82798d3ff2b9f 100644 (file)
@@ -1097,11 +1097,11 @@ mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
        x86_call_code (code, (guint8*)func);
 }
 
-static void
-handler_block_trampoline_helper (gpointer *ptr)
+static gpointer
+handler_block_trampoline_helper (void)
 {
        MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
-       *ptr = jit_tls->handler_block_return_address;
+       return jit_tls->handler_block_return_address;
 }
 
 gpointer
@@ -1116,21 +1116,25 @@ mono_arch_create_handler_block_trampoline (void)
        This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
        */
 
+       /*
+        * We are in a method frame after the call emitted by OP_CALL_HANDLER.
+        */
+
        if (mono_get_jit_tls_offset () != -1) {
                code = mono_x86_emit_tls_get (code, X86_EAX, mono_get_jit_tls_offset ());
                x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoJitTlsData, handler_block_return_address), 4);
-               /*simulate a call*/
-               /*Fix stack alignment*/
-               x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x8);
-               x86_push_reg (code, X86_EAX);
-               x86_jump_code (code, tramp);
        } else {
                /*Slow path uses a c helper*/
-               x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x8);
-               x86_push_reg (code, X86_ESP);
-               x86_push_imm (code, tramp);
-               x86_jump_code (code, handler_block_trampoline_helper);
+               x86_call_code (code, handler_block_trampoline_helper);
        }
+       /* Simulate a call */
+       /*Fix stack alignment*/
+       x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x4);
+       /* This is the address the trampoline will return to */
+       x86_push_reg (code, X86_EAX);
+       /* Dummy trampoline argument, since we call the generic trampoline directly */
+       x86_push_imm (code, 0);
+       x86_jump_code (code, tramp);
 
        nacl_global_codeman_validate (&buf, tramp_size, &code);
 
@@ -1187,7 +1191,7 @@ mono_arch_get_gsharedvt_arg_trampoline (MonoDomain *domain, gpointer arg, gpoint
        return start;
 }
 
-#if defined(MONOTOUCH) || defined(MONO_EXTENSIONS)
+#if defined(MONO_GSHARING)
 
 #include "../../../mono-extensions/mono/mini/tramp-x86-gsharedvt.c"
 
index aeb7b55c873d1eb2d7a46f152a9166c18463087d..02cfbbd40a6cacef016398732a3dc4323c730413 100644 (file)
@@ -1,4 +1,5 @@
 using System;
+using System.Reflection;
 using System.Runtime.InteropServices;
 
 public class Test 
@@ -51,7 +52,8 @@ public class Test
                object itf;
        }
 
-       // Size should be 12 in both 32 and 64 bits
+       // Size should be 16 in both 32 and 64 bits win/linux
+       // Size should be 12 on 32bits OSX size alignment of long is 4
        [StructLayout (LayoutKind.Explicit)]
        struct TestStruct8 {
                [FieldOffset (0)]
@@ -69,7 +71,8 @@ public class Test
                public ulong b;
        }
 
-       // Size should be 11 in both 32 and 64 bits
+       // Size should be 16 in both 32 and 64 bits
+       // Size should be 12 on 32bits OSX size alignment of long is 4
        [StructLayout (LayoutKind.Explicit)]
        struct TestStruct10 {
                [FieldOffset (0)]
@@ -95,6 +98,34 @@ public class Test
                public int b;
        }
 
+       // Size should always be 12, since pack = 0, size = 0 and min alignment = 4
+       //When pack is not set, we default to 8, so min (8, min alignment) -> 4
+       [StructLayout (LayoutKind.Explicit)]
+       struct TestStruct13 {
+               [FieldOffset(0)]
+               int one;
+               [FieldOffset(4)]
+               int two;
+               [FieldOffset(8)]
+               int three;
+       }
+
+       // Size should always be 12, since pack = 8, size = 0 and min alignment = 4
+       //It's aligned to min (pack, min alignment) -> 4
+       [StructLayout (LayoutKind.Explicit)]
+       struct TestStruct14 {
+               [FieldOffset(0)]
+               int one;
+               [FieldOffset(4)]
+               int two;
+               [FieldOffset(8)]
+               int three;
+       }
+       static bool IsOSX ()
+       {
+               return (int)typeof (Environment).GetMethod ("get_Platform", BindingFlags.Static | BindingFlags.NonPublic).Invoke (null, null) == 6;
+       }
+
        public unsafe static int Main () 
        {
                ///
@@ -181,16 +212,27 @@ public class Test
                // a VARIANT is 
                if (Marshal.SizeOf (typeof (TestStruct7)) != 16)
                        return 13;
-               if (Marshal.SizeOf (typeof (TestStruct8)) != 16)
-                       return 14;
+               if (IsOSX () && IntPtr.Size == 4) {
+                       if (Marshal.SizeOf (typeof (TestStruct8)) != 12)
+                               return 14;
+                       if (Marshal.SizeOf (typeof (TestStruct10)) != 12)
+                               return 16;
+               } else {
+                       if (Marshal.SizeOf (typeof (TestStruct8)) != 16)
+                               return 14;
+                       if (Marshal.SizeOf (typeof (TestStruct10)) != 16)
+                               return 16;
+               }
                if (Marshal.SizeOf (typeof (TestStruct9)) != 12)
                        return 15;
-               if (Marshal.SizeOf (typeof (TestStruct10)) != 16)
-                       return 16;
                if (Marshal.SizeOf (typeof (TestStruct11)) != 11)
                        return 17;
                if (Marshal.SizeOf (typeof (TestStruct12)) != 6)
                        return 18;
+               if (Marshal.SizeOf (typeof (TestStruct13)) != 12)
+                       return 19;
+               if (Marshal.SizeOf (typeof (TestStruct14)) != 12)
+                       return 20;
                return 0;
        }
 }
index 79455ad9c435c889e9e2fb5289b365324b2ea29a..c8c70007bc751d0a55d612c230a28450c79e968f 100755 (executable)
@@ -79,6 +79,35 @@ static inline gint64 InterlockedAdd64(volatile gint64 *dest, gint64 add)
 }
 #endif
 
+#if defined(_MSC_VER) && !defined(InterlockedAdd)
+/* MSVC before 2013 only defines InterlockedAdd* for the Itanium architecture */
+static inline gint32 InterlockedAdd(volatile gint32 *dest, gint32 add)
+{
+       return InterlockedExchangeAdd (dest, add) + add;
+}
+#endif
+
+#if defined(_MSC_VER) && !defined(InterlockedAdd64)
+#if defined(InterlockedExchangeAdd64)
+/* This may be defined only on amd64 */
+static inline gint64 InterlockedAdd64(volatile gint64 *dest, gint64 add)
+{
+       return InterlockedExchangeAdd64 (dest, add) + add;
+}
+#else
+static inline gint64 InterlockedAdd64(volatile gint64 *dest, gint64 add)
+{
+       gint64 prev_value;
+
+       do {
+               prev_value = *dest;
+       } while (prev_value != InterlockedCompareExchange64(dest, prev_value + add, prev_value));
+
+       return prev_value + add;
+}
+#endif
+#endif
+
 /* And now for some dirty hacks... The Windows API doesn't
  * provide any useful primitives for this (other than getting
  * into architecture-specific madness), so use CAS. */
index 6772dacfd503424548de5370bfb2792b81bb32c6..a533a9f01e33867044ce77558d92992f1bfac588 100644 (file)
 #ifdef _MSC_VER
 
 #include <math.h>
+
+#if _MSC_VER < 1800 /* VS 2013 */
+#define strtoull _strtoui64
+#endif
+
 #include <float.h>
 #define isnan(x)       _isnan(x)
 #define trunc(x)       (((x) < 0) ? ceil((x)) : floor((x)))
index 5278c00c13357af4cb5ba3a41dc11131d074207e..36c7fd6df93abbdec09fb325c2957bad9dbe1e61 100644 (file)
@@ -86,6 +86,8 @@ mono_file_map_fileio (size_t length, int flags, int fd, guint64 offset, void **r
                return NULL;
        }
        bytes_read = read (fd, ptr, length);
+       if (bytes_read != length)
+               return NULL;
        lseek (fd, cur_offset, SEEK_SET);
        *ret_handle = NULL;
        return ptr;
index 5bd290f75ef1906e73edc4b4feda9b61be8ef09c..dab3a5579e2dfbbd8cac0f47179fae0a2cd3a92a 100644 (file)
@@ -561,7 +561,7 @@ get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *s
        char buf [256];
        char *s;
        int hz = get_user_hz ();
-       guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, iowait_ticks, irq_ticks = 0, sirq_ticks = 0;
+       guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
        FILE *f = fopen ("/proc/stat", "r");
        if (!f)
                return;
@@ -583,7 +583,7 @@ get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *s
                nice_ticks = strtoull (data, &data, 10);
                system_ticks = strtoull (data, &data, 10);
                idle_ticks = strtoull (data, &data, 10);
-               iowait_ticks = strtoull (data, &data, 10);
+               strtoull (data, &data, 10); /* iowait_ticks */
                irq_ticks = strtoull (data, &data, 10);
                sirq_ticks = strtoull (data, &data, 10);
                break;
index 8dba68fe7fba6b44855283f4fedaa16d2d49e013..a3a4e491aa2da02b7efd78d5bbcf8a84a86b783f 100644 (file)
@@ -9,10 +9,17 @@
 
 #include <config.h>
 
+#if defined(__OpenBSD__) || defined(__FreeBSD__)
+#include <pthread.h>
+#include <pthread_np.h>
+#endif
+
 #include <mono/utils/mono-compiler.h>
 #include <mono/utils/mono-semaphore.h>
 #include <mono/utils/mono-threads.h>
 #include <mono/utils/mono-tls.h>
+#include <mono/utils/gc_wrapper.h>
+#include <mono/utils/mono-mmap.h>
 #include <mono/metadata/threads-types.h>
 
 #include <errno.h>
 extern int tkill (pid_t tid, int signal);
 #endif
 
+#if defined(PLATFORM_MACOSX) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
+void *pthread_get_stackaddr_np(pthread_t);
+size_t pthread_get_stacksize_np(pthread_t);
+#endif
+
 #if defined(_POSIX_VERSION) || defined(__native_client__)
 #include <signal.h>
 
+#if defined(__native_client__)
+void nacl_shutdown_gc_thread(void);
+#endif
+
 typedef struct {
        void *(*start_routine)(void*);
        void *arg;
        int flags;
        MonoSemType registered;
-} ThreadStartInfo;
-
+       HANDLE handle;
+} StartInfo;
 
 static void*
 inner_start_thread (void *arg)
 {
-       ThreadStartInfo *start_info = arg;
+       StartInfo *start_info = arg;
        void *t_arg = start_info->arg;
-       int post_result;
+       int res;
        void *(*start_func)(void*) = start_info->start_routine;
+       guint32 flags = start_info->flags;
        void *result;
+       HANDLE handle;
+       MonoThreadInfo *info;
+
+       /* Register the thread with the io-layer */
+       handle = wapi_create_thread_handle ();
+       if (!handle) {
+               res = MONO_SEM_POST (&(start_info->registered));
+               g_assert (!res);
+               return NULL;
+       }
+       start_info->handle = handle;
 
-       mono_thread_info_attach (&result)->runtime_thread = TRUE;
+       if (!(flags & CREATE_NO_DETACH)) {
+               res = mono_gc_pthread_detach (pthread_self ());
+               g_assert (!res);
+       }
 
-       post_result = MONO_SEM_POST (&(start_info->registered));
-       g_assert (!post_result);
+       info = mono_thread_info_attach (&result);
+       info->runtime_thread = TRUE;
+
+       if (flags & CREATE_SUSPENDED) {
+               info->create_suspended = TRUE;
+               MONO_SEM_INIT (&info->create_suspended_sem, 0);
+       }
 
+       /* start_info is not valid after this */
+       res = MONO_SEM_POST (&(start_info->registered));
+       g_assert (!res);
+       start_info = NULL;
+
+       if (flags & CREATE_SUSPENDED) {
+               while (MONO_SEM_WAIT (&info->create_suspended_sem) != 0 &&
+                          errno == EINTR);
+               MONO_SEM_DESTROY (&info->create_suspended_sem);
+       }
+
+       /* Run the actual main function of the thread */
        result = start_func (t_arg);
-       g_assert (!mono_domain_get ());
 
+       /*
+       g_assert (!mono_domain_get ());
        mono_thread_info_dettach ();
+       */
+
+#if defined(__native_client__)
+       nacl_shutdown_gc_thread();
+#endif
+
+       wapi_thread_set_exit_code (GPOINTER_TO_UINT (result), handle);
 
+       // FIXME: Why is this needed ?
+       mono_gc_pthread_exit (NULL);
+
+       g_assert_not_reached ();
        return result;
 }
 
-int
-mono_threads_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
+HANDLE
+mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
 {
-       ThreadStartInfo *start_info;
-       int result;
-
-       start_info = g_malloc0 (sizeof (ThreadStartInfo));
-       if (!start_info)
-               return ENOMEM;
-       MONO_SEM_INIT (&(start_info->registered), 0);
-       start_info->arg = arg;
-       start_info->start_routine = start_routine;
-
-       result = mono_threads_get_callbacks ()->mono_gc_pthread_create (new_thread, attr, inner_start_thread, start_info);
-       if (result == 0) {
-               while (MONO_SEM_WAIT (&(start_info->registered)) != 0) {
-                       /*if (EINTR != errno) ABORT("sem_wait failed"); */
-               }
+       pthread_attr_t attr;
+       int res;
+       pthread_t thread;
+       StartInfo start_info;
+
+       res = pthread_attr_init (&attr);
+       g_assert (!res);
+
+       if (stack_size == 0) {
+#if HAVE_VALGRIND_MEMCHECK_H
+               if (RUNNING_ON_VALGRIND)
+                       stack_size = 1 << 20;
+               else
+                       stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+#else
+               stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
+#endif
        }
-       MONO_SEM_DESTROY (&(start_info->registered));
-       g_free (start_info);
-       return result;
+
+#ifdef PTHREAD_STACK_MIN
+       if (stack_size < PTHREAD_STACK_MIN)
+               stack_size = PTHREAD_STACK_MIN;
+#endif
+
+#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
+       res = pthread_attr_setstacksize (&attr, stack_size);
+       g_assert (!res);
+#endif
+
+       memset (&start_info, 0, sizeof (StartInfo));
+       start_info.start_routine = (gpointer)start_routine;
+       start_info.arg = arg;
+       start_info.flags = creation_flags;
+       MONO_SEM_INIT (&(start_info.registered), 0);
+
+       /* Actually start the thread */
+       res = mono_threads_get_callbacks ()->mono_gc_pthread_create (&thread, &attr, inner_start_thread, &start_info);
+       if (res) {
+               // FIXME:
+               g_assert_not_reached ();
+       }
+
+       /* Wait until the thread register itself in various places */
+       while (MONO_SEM_WAIT (&(start_info.registered)) != 0) {
+               /*if (EINTR != errno) ABORT("sem_wait failed"); */
+       }
+       MONO_SEM_DESTROY (&(start_info.registered));
+
+       if (out_tid)
+               *out_tid = thread;
+
+       return start_info.handle;
+}
+
+/*
+ * mono_threads_core_resume_created:
+ *
+ *   Resume a newly created thread created using CREATE_SUSPENDED.
+ */
+void
+mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
+{
+       MONO_SEM_POST (&info->create_suspended_sem);
+}
+
+void
+mono_threads_core_get_stack_bounds (guint8 **staddr, size_t *stsize)
+{
+#if defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
+       /* Mac OS X */
+       *staddr = (guint8*)pthread_get_stackaddr_np (pthread_self());
+       *stsize = pthread_get_stacksize_np (pthread_self());
+
+
+#ifdef TARGET_OSX
+       /*
+        * Mavericks reports stack sizes as 512kb:
+        * http://permalink.gmane.org/gmane.comp.java.openjdk.hotspot.devel/11590
+        * https://bugs.openjdk.java.net/browse/JDK-8020753
+        */
+       if (*stsize == 512 * 1024)
+               *stsize = 2048 * mono_pagesize ();
+#endif
+
+       /* staddr points to the start of the stack, not the end */
+       *staddr -= *stsize;
+
+       /* When running under emacs, sometimes staddr is not aligned to a page size */
+       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize() - 1));
+       return;
+
+#elif (defined(HAVE_PTHREAD_GETATTR_NP) || defined(HAVE_PTHREAD_ATTR_GET_NP)) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
+       /* Linux, BSD */
+
+       pthread_attr_t attr;
+       guint8 *current = (guint8*)&attr;
+
+       *staddr = NULL;
+       *stsize = (size_t)-1;
+
+       pthread_attr_init (&attr);
+
+#if     defined(HAVE_PTHREAD_GETATTR_NP)
+       /* Linux */
+       pthread_getattr_np (pthread_self(), &attr);
+
+#elif   defined(HAVE_PTHREAD_ATTR_GET_NP)
+       /* BSD */
+       pthread_attr_get_np (pthread_self(), &attr);
+
+#else
+#error         Cannot determine which API is needed to retrieve pthread attributes.
+#endif
+
+       pthread_attr_getstack (&attr, (void**)staddr, stsize);
+       pthread_attr_destroy (&attr);
+
+       if (*staddr)
+               g_assert ((current > *staddr) && (current < *staddr + *stsize));
+
+       /* When running under emacs, sometimes staddr is not aligned to a page size */
+       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
+       return;
+
+#elif defined(__OpenBSD__)
+       /* OpenBSD */
+       /* TODO :   Determine if this code is actually still needed. It may already be covered by the case above. */
+
+       pthread_attr_t attr;
+       guint8 *current = (guint8*)&attr;
+
+       *staddr = NULL;
+       *stsize = (size_t)-1;
+
+       pthread_attr_init (&attr);
+
+       stack_t ss;
+       int rslt;
+
+       rslt = pthread_stackseg_np(pthread_self(), &ss);
+       g_assert (rslt == 0);
+
+       *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
+       *stsize = ss.ss_size;
+
+       pthread_attr_destroy (&attr);
+
+       if (*staddr)
+               g_assert ((current > *staddr) && (current < *staddr + *stsize));
+
+       /* When running under emacs, sometimes staddr is not aligned to a page size */
+       *staddr = (guint8*)((gssize)*staddr & ~(mono_pagesize () - 1));
+       return;
+
+#elif defined(sun) || defined(__native_client__)
+       /* Solaris/Illumos, NaCl */
+       pthread_attr_t attr;
+       pthread_attr_init (&attr);
+       pthread_attr_getstacksize (&attr, &stsize);
+       pthread_attr_destroy (&attr);
+       *staddr = NULL;
+       return;
+
+#else
+       /* FIXME:   It'd be better to use the 'error' preprocessor macro here so we know
+                   at compile-time if the target platform isn't supported. */
+#warning "Unable to determine how to retrieve a thread's stack-bounds for this platform in 'mono_thread_get_stack_bounds()'."
+       *staddr = NULL;
+       *stsize = 0;
+       return;
+#endif
+}
+
+gboolean
+mono_threads_core_yield (void)
+{
+       return sched_yield () == 0;
 }
 
 #if !defined (__MACH__)
index 4ed9dd13f99b4944e2791c1ad0abf48937640f0c..92457cc9b8984dea182966482530c9d35fc23314 100644 (file)
@@ -82,14 +82,16 @@ inner_start_thread (LPVOID arg)
        DWORD result;
        gboolean suspend = start_info->suspend;
        HANDLE suspend_event = start_info->suspend_event;
+       MonoThreadInfo *info;
 
-       mono_thread_info_attach (&result)->runtime_thread = TRUE;
+       info = mono_thread_info_attach (&result);
+       info->runtime_thread = TRUE;
+       info->create_suspended = suspend;
 
        post_result = MONO_SEM_POST (&(start_info->registered));
        g_assert (!post_result);
 
-       if (suspend)
-       {
+       if (suspend) {
                WaitForSingleObject (suspend_event, INFINITE); /* caller will suspend the thread before setting the event. */
                CloseHandle (suspend_event);
        }
@@ -104,11 +106,11 @@ inner_start_thread (LPVOID arg)
 }
 
 HANDLE
-mono_threads_CreateThread (LPSECURITY_ATTRIBUTES attributes, SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine,
-               LPVOID arg, DWORD creation_flags, LPDWORD thread_id)
+mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start_routine, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
 {
        ThreadStartInfo *start_info;
        HANDLE result;
+       DWORD thread_id;
 
        start_info = g_malloc0 (sizeof (ThreadStartInfo));
        if (!start_info)
@@ -118,27 +120,26 @@ mono_threads_CreateThread (LPSECURITY_ATTRIBUTES attributes, SIZE_T stack_size,
        start_info->start_routine = start_routine;
        start_info->suspend = creation_flags & CREATE_SUSPENDED;
        creation_flags &= ~CREATE_SUSPENDED;
-       if (start_info->suspend)
-       {
+       if (start_info->suspend) {
                start_info->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
                if (!start_info->suspend_event)
                        return NULL;
        }
 
-       result = CreateThread (attributes, stack_size, inner_start_thread, start_info, creation_flags, thread_id);
-
+       result = CreateThread (NULL, stack_size, inner_start_thread, start_info, creation_flags, &thread_id);
        if (result) {
                while (MONO_SEM_WAIT (&(start_info->registered)) != 0) {
                        /*if (EINTR != errno) ABORT("sem_wait failed"); */
                }
-               if (start_info->suspend)
-               {
+               if (start_info->suspend) {
                        g_assert (SuspendThread (result) != (DWORD)-1);
                        SetEvent (start_info->suspend_event);
                }
-       }
-       else if (start_info->suspend)
+       } else if (start_info->suspend) {
                CloseHandle (start_info->suspend_event);
+       }
+       if (out_tid)
+               *out_tid = thread_id;
        MONO_SEM_DESTROY (&(start_info->registered));
        g_free (start_info);
        return result;
@@ -163,4 +164,47 @@ mono_native_thread_create (MonoNativeThreadId *tid, gpointer func, gpointer arg)
        return CreateThread (NULL, 0, (func), (arg), 0, (tid)) != NULL;
 }
 
+void
+mono_threads_core_resume_created (MonoThreadInfo *info, MonoNativeThreadId tid)
+{
+       HANDLE handle;
+
+       handle = OpenThread (THREAD_ALL_ACCESS, TRUE, tid);
+       g_assert (handle);
+       ResumeThread (handle);
+       CloseHandle (handle);
+}
+
+#if HAVE_DECL___READFSDWORD==0
+static __inline__ __attribute__((always_inline))
+unsigned long long
+__readfsdword (unsigned long offset)
+{
+       unsigned long value;
+       //      __asm__("movl %%fs:%a[offset], %k[value]" : [value] "=q" (value) : [offset] "irm" (offset));
+   __asm__ volatile ("movl    %%fs:%1,%0"
+     : "=r" (value) ,"=m" ((*(volatile long *) offset)));
+       return value;
+}
+#endif
+
+void
+mono_threads_core_get_stack_bounds (guint8 **staddr, size_t *stsize)
+{
+       /* Windows */
+       /* http://en.wikipedia.org/wiki/Win32_Thread_Information_Block */
+       void* tib = (void*)__readfsdword(0x18);
+       guint8 *stackTop = (guint8*)*(int*)((char*)tib + 4);
+       guint8 *stackBottom = (guint8*)*(int*)((char*)tib + 8);
+
+       *staddr = stackBottom;
+       *stsize = stackTop - stackBottom;
+}
+
+gboolean
+mono_threads_core_yield (void)
+{
+       return SwitchToThread ();
+}
+
 #endif
index 2fc08a59844b5304ba04f7ddd5abde0824d51c5e..5138427ed7c5c2de57d11eaffaa84d4420ef4af4 100644 (file)
@@ -14,8 +14,6 @@
 #include <mono/utils/mono-tls.h>
 #include <mono/utils/hazard-pointer.h>
 #include <mono/utils/mono-memory-model.h>
-#include <mono/metadata/appdomain.h>
-#include <mono/metadata/domain-internals.h>
 
 #include <errno.h>
 
@@ -447,9 +445,17 @@ mono_thread_info_resume (MonoNativeThreadId tid)
        gboolean result = TRUE;
        MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();      
        MonoThreadInfo *info = mono_thread_info_lookup (tid); /*info on HP1*/
+
        if (!info)
                return FALSE;
 
+       if (info->create_suspended) {
+               /* Have to special case this, as the normal suspend/resume pair are racy, they don't work if he resume is received before the suspend */
+               info->create_suspended = FALSE;
+               mono_threads_core_resume_created (info, tid);
+               return TRUE;
+       }
+
        MONO_SEM_WAIT_UNITERRUPTIBLE (&info->suspend_semaphore);
 
        THREADS_DEBUG ("resume %x IN COUNT %d\n",tid, info->suspend_count);
@@ -690,3 +696,52 @@ mono_thread_info_is_async_context (void)
                return FALSE;
 }
 
+/*
+ * mono_threads_create_thread:
+ *
+ *   Create a new thread executing START with argument ARG. Store its id into OUT_TID.
+ * Returns: a windows or io-layer handle for the thread.
+ */
+HANDLE
+mono_threads_create_thread (LPTHREAD_START_ROUTINE start, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid)
+{
+       return mono_threads_core_create_thread (start, arg, stack_size, creation_flags, out_tid);
+}
+
+/*
+ * mono_thread_info_get_stack_bounds:
+ *
+ *   Return the address and size of the current threads stack. Return NULL as the 
+ * stack address if the stack address cannot be determined.
+ */
+void
+mono_thread_info_get_stack_bounds (guint8 **staddr, size_t *stsize)
+{
+       return mono_threads_core_get_stack_bounds (staddr, stsize);
+}
+
+gboolean
+mono_thread_info_yield (void)
+{
+       return mono_threads_core_yield ();
+}
+
+gpointer
+mono_thread_info_tls_get (THREAD_INFO_TYPE *info, MonoTlsKey key)
+{
+       return ((MonoThreadInfo*)info)->tls [key];
+}
+
+/*
+ * mono_threads_info_tls_set:
+ *
+ *   Set the TLS key to VALUE in the info structure. This can be used to obtain
+ * values of TLS variables for threads other than the current thread.
+ * This should only be used for infrequently changing TLS variables, and it should
+ * be paired with setting the real TLS variable since this provides no GC tracking.
+ */
+void
+mono_thread_info_tls_set (THREAD_INFO_TYPE *info, MonoTlsKey key, gpointer value)
+{
+       ((MonoThreadInfo*)info)->tls [key] = value;
+}
index d06aea6e724569010f8d649c0933d7de97046a00..aaf2a174ade00b268a31116d278b3bd0b5ebf7ec 100644 (file)
@@ -14,6 +14,7 @@
 #include <mono/utils/mono-stack-unwinding.h>
 #include <mono/utils/mono-linked-list-set.h>
 #include <mono/utils/mono-mutex.h>
+#include <mono/utils/mono-tls.h>
 
 #include <glib.h>
 
@@ -26,6 +27,8 @@ typedef HANDLE MonoNativeThreadHandle; /* unused */
 
 typedef DWORD mono_native_thread_return_t;
 
+#define MONO_NATIVE_THREAD_ID_TO_UINT(tid) (tid)
+
 #else
 
 #include <pthread.h>
@@ -47,6 +50,8 @@ typedef pthread_t MonoNativeThreadId;
 
 typedef void* mono_native_thread_return_t;
 
+#define MONO_NATIVE_THREAD_ID_TO_UINT(tid) (gsize)(tid)
+
 #endif /* #ifdef HOST_WIN32 */
 
 /*
@@ -132,6 +137,18 @@ typedef struct {
         * operations like locking without having to pass an 'async' parameter around.
         */
        gboolean is_async_context;
+
+       gboolean create_suspended;
+
+       /* Semaphore used to implement CREATE_SUSPENDED */
+       MonoSemType create_suspended_sem;
+
+       /*
+        * Values of TLS variables for this thread.
+        * This can be used to obtain the values of TLS variable for threads
+        * other than the current one.
+        */
+       gpointer tls [TLS_KEY_NUM];
 } MonoThreadInfo;
 
 typedef struct {
@@ -251,10 +268,22 @@ mono_thread_info_set_is_async_context (gboolean async_context) MONO_INTERNAL;
 gboolean
 mono_thread_info_is_async_context (void) MONO_INTERNAL;
 
-#if !defined(HOST_WIN32)
+void
+mono_thread_info_get_stack_bounds (guint8 **staddr, size_t *stsize);
 
-int
-mono_threads_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) MONO_INTERNAL;
+gboolean
+mono_thread_info_yield (void) MONO_INTERNAL;
+
+gpointer
+mono_thread_info_tls_get (THREAD_INFO_TYPE *info, MonoTlsKey key);
+
+void
+mono_thread_info_tls_set (THREAD_INFO_TYPE *info, MonoTlsKey key, gpointer value);
+
+HANDLE
+mono_threads_create_thread (LPTHREAD_START_ROUTINE start, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid);
+
+#if !defined(HOST_WIN32)
 
 #if !defined(__MACH__)
 /*Use this instead of pthread_kill */
@@ -262,12 +291,6 @@ int
 mono_threads_pthread_kill (THREAD_INFO_TYPE *info, int signum) MONO_INTERNAL;
 #endif
 
-#else  /* !defined(HOST_WIN32) */
-
-HANDLE
-       mono_threads_CreateThread (LPSECURITY_ATTRIBUTES attributes, SIZE_T stack_size, LPTHREAD_START_ROUTINE start_routine, LPVOID arg, DWORD creation_flags, LPDWORD thread_id);
-
-
 #endif /* !defined(HOST_WIN32) */
 
 /* Plartform specific functions DON'T use them */
@@ -279,6 +302,10 @@ void mono_threads_platform_free (THREAD_INFO_TYPE *info) MONO_INTERNAL;
 void mono_threads_core_interrupt (THREAD_INFO_TYPE *info) MONO_INTERNAL;
 void mono_threads_core_abort_syscall (THREAD_INFO_TYPE *info) MONO_INTERNAL;
 gboolean mono_threads_core_needs_abort_syscall (void) MONO_INTERNAL;
+HANDLE mono_threads_core_create_thread (LPTHREAD_START_ROUTINE start, gpointer arg, guint32 stack_size, guint32 creation_flags, MonoNativeThreadId *out_tid) MONO_INTERNAL;
+void mono_threads_core_resume_created (THREAD_INFO_TYPE *info, MonoNativeThreadId tid) MONO_INTERNAL;
+void mono_threads_core_get_stack_bounds (guint8 **staddr, size_t *stsize) MONO_INTERNAL;
+gboolean mono_threads_core_yield (void) MONO_INTERNAL;
 
 MonoNativeThreadId mono_native_thread_id_get (void) MONO_INTERNAL;
 
index 809ee028d46371f0d71379a9dd065bd0be3469ba..9e8160baea94d1644bd538b5e9c16a5c44b36c5f 100644 (file)
@@ -28,6 +28,9 @@ SUPPORT_FILES = $(symlinks) mono-wrapper etc/mono/config
 if ONLY_MONOTOUCH
 build_profiles = monotouch
 else
+if ONLY_XAMMAC
+build_profiles = xammac
+else
 build_profiles = 
 
 if INSTALL_2_0
@@ -41,7 +44,7 @@ al_profile = net_4_0
 endif
 
 if INSTALL_4_5
-build_profiles += net_4_5
+build_profiles += net_4_5 xbuild_12
 al_profile = net_4_5
 endif
 
@@ -53,8 +56,13 @@ if INSTALL_MONOTOUCH
 build_profiles += monotouch monotouch_runtime
 endif
 
+if INSTALL_XAMMAC
+build_profiles += xammac
+endif
+
 test_profiles = $(build_profiles)
 
+endif
 endif
 
 if BUILD_MCS
index e0273c1d06034870d066e58def44dc4f660f27c2..7a697cd2cc1f43c89cdbdf3a23b3db5552388fbc 100644 (file)
@@ -45,6 +45,10 @@ bin_SCRIPTS += $(scripts_4_0)
 bin_SCRIPTS += dmcs
 endif
 
+if INSTALL_4_5
+bin_SCRIPTS += xbuild
+endif
+
 scripts_4_0_umask = \
        makecert$(SCRIPT_SUFFIX)                \
        sn$(SCRIPT_SUFFIX)
@@ -96,7 +100,6 @@ scripts_4_0 = \
        sqlmetal$(SCRIPT_SUFFIX)                \
        sqlsharp$(SCRIPT_SUFFIX)                \
        svcutil$(SCRIPT_SUFFIX)                 \
-       xbuild$(SCRIPT_SUFFIX)                  \
        ccrewrite$(SCRIPT_SUFFIX)               \
        cccheck$(SCRIPT_SUFFIX)                 \
        mdbrebase$(SCRIPT_SUFFIX)
@@ -149,6 +152,7 @@ EXTRA_DIST =                        \
        mono-find-provides.in   \
        mono-find-requires.in   \
        peverify.in                     \
+       xbuild.in                       \
        update_submodules               \
        mcs.in                          \
        gmcs.in                         \
@@ -240,6 +244,10 @@ nunit-console4$(SCRIPT_SUFFIX): $(SCRIPT_IN) Makefile
        $(REWRITE4_DEBUG) -e 's,@''exe_name@,nunit-console,g' $(srcdir)/$(SCRIPT_IN) | $(FILTER) > $@.tmp
        mv -f $@.tmp $@
 
+xbuild: xbuild.in Makefile
+       $(REWRITE_COMMON) $(srcdir)/xbuild.in > $@.tmp
+       mv -f $@.tmp $@
+
 #FIXME: this is not the correct rule for mod.bat.
 mod$(SCRIPT_SUFFIX): mod.in Makefile
        $(REWRITE2) -e "s,@""exe_name@,mod,g" $(srcdir)/mod.in > $@.tmp
diff --git a/scripts/xbuild.in b/scripts/xbuild.in
new file mode 100644 (file)
index 0000000..bbaac3d
--- /dev/null
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec @bindir@/mono $MONO_OPTIONS @mono_instdir@/xbuild/12.0/bin/xbuild.exe "$@"
index 4d0383a36208f38b19aa8ab0a58d1dbbcee8bb53..a41a2fe2ae6eecff173d94e15a5062b6ed33fd5a 100644 (file)
@@ -361,8 +361,11 @@ namespace Mono.Tools.LocaleBuilder
 
                        var territory2dayofweek = new Dictionary<string, DayOfWeek> (StringComparer.OrdinalIgnoreCase);
                        foreach (XmlNode entry in supplemental.SelectNodes ("supplementalData/weekData/firstDay")) {
-                               DayOfWeek dow;
 
+                               if (entry.Attributes ["alt"] != null)
+                                       continue;
+
+                               DayOfWeek dow;
                                switch (entry.Attributes["day"].Value) {
                                case "mon":
                                        dow = DayOfWeek.Monday;
@@ -381,8 +384,9 @@ namespace Mono.Tools.LocaleBuilder
                                }
 
                                var territories = entry.Attributes["territories"].Value.Split ();
-                               foreach (var t in territories)
-                                       territory2dayofweek[t] = dow;
+                               foreach (var t in territories) {
+                                       territory2dayofweek.Add (t, dow);
+                               }
                        }
 
                        var territory2wr = new Dictionary<string, CalendarWeekRule> (StringComparer.OrdinalIgnoreCase);