提交 853efd2b 编写于 作者: C CyrusNajmabadi

Merge remote-tracking branch 'upstream/master' into gotodefPerf

......@@ -221,6 +221,7 @@
<VSSDKComponentModelHostVersion>12.0.4</VSSDKComponentModelHostVersion>
<VsWebsiteInteropVersion>8.0.0.0-alpha</VsWebsiteInteropVersion>
<xunitVersion>2.2.0-beta4-build3444</xunitVersion>
<xunitassertVersion>2.2.0-beta4-build3444</xunitassertVersion>
<xunitconsolenetcoreVersion>1.0.2-prerelease-00104</xunitconsolenetcoreVersion>
<xunitrunnerconsoleVersion>2.2.0-beta4-build3444</xunitrunnerconsoleVersion>
<xunitrunnervisualstudioVersion>2.2.0-beta4-build1194</xunitrunnervisualstudioVersion>
......
......@@ -146,14 +146,13 @@
<Compile Include="Emit\EditAndContinue\LocalSlotMappingTests.cs" />
<Compile Include="Emit\EmitCustomModifiers.cs" />
<Compile Include="Emit\EmitErrorTests.cs" />
<Compile Include="Emit\EmitMetadata.cs" />
<Compile Include="Emit\EmitMetadataTests.cs" />
<Compile Include="Emit\EmitMetadataTestBase.cs" />
<Compile Include="Attributes\EmitTestStrongNameProvider.cs" />
<Compile Include="Emit\EndToEndTests.cs" />
<Compile Include="Emit\EntryPointTests.cs" />
<Compile Include="Emit\NoPiaEmbedTypes.cs" />
<Compile Include="Emit\OptionalArgumentsTests.cs" />
<Compile Include="Emit\OutputStreams.cs" />
<Compile Include="Emit\ResourceTests.cs" />
<Compile Include="CodeGen\CodeGenScriptTests.cs" />
<Compile Include="PDB\CheckSumTest.cs" />
......
......@@ -9,7 +9,7 @@ namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public static class LocalFunctionTestsUtil
{
public static IMethodSymbol FindLocalFunction(this CommonTestBase.CompilationVerifier verifier, string localFunctionName)
public static IMethodSymbol FindLocalFunction(this CompilationVerifier verifier, string localFunctionName)
{
localFunctionName = (char)GeneratedNameKind.LocalFunction + "__" + localFunctionName;
var methods = verifier.TestData.GetMethodsByName();
......
......@@ -2,6 +2,7 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
......@@ -703,14 +704,6 @@ public static IEnumerable Power(int number, int exponent)
CompileAndVerify(text, expectedOutput: expectedOutput);
}
// When ReflectionEmit supports writing exception handler info, this method
// can be removed and CompileAndVerify references above will resolve to
// the overload that emits with both CCI and ReflectionEmit. (Bug #7012)
private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null)
{
return base.CompileAndVerify(source: source, expectedOutput: expectedOutput);
}
[WorkItem(540719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540719")]
[Fact]
public void LabelBetweenLocalAndInitialize()
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit
{
internal class NameResolver
{
public string GetDebugInformationFileName(SyntaxTree syntaxTree)
{
throw new NotImplementedException();
}
public Stream GetXmlInclude(SyntaxTree syntaxTree, string xmlIncludeFile)
{
throw new NotImplementedException();
}
}
}
......@@ -2214,7 +2214,7 @@ class C
var emitResult1 = c.Emit(peStream: peStream1, pdbStream: pdbStream);
var emitResult2 = c.Emit(peStream: peStream2);
PdbValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2);
MetadataValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2);
}
[Fact]
......
......@@ -483,7 +483,7 @@ static System.Action<object> F()
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "value__").WithArguments("A.value__"));
// PEVerify should not report "Field value__ ... is not marked RTSpecialName".
var verifier = new CompilationVerifier(this, compilation);
var verifier = new CompilationVerifier(compilation);
verifier.EmitAndVerify(
"Error: Field name value__ is reserved for Enums only.",
"Error: Field name value__ is reserved for Enums only.",
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using static Microsoft.CodeAnalysis.Test.Utilities.CommonTestBase;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
......
......@@ -899,6 +899,7 @@
<InternalsVisibleToTest Include="Roslyn.Test.Utilities.Desktop" />
<InternalsVisibleToTest Include="Roslyn.Test.Utilities.FX45" />
<InternalsVisibleToTest Include="Roslyn.Test.Utilities" />
<InternalsVisibleToTest Include="Roslyn.Test.PdbUtilities" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CompilerServer.UnitTests" />
<InternalsVisibleToMoq Include="DynamicProxyGenAssembly2" />
</ItemGroup>
......
......@@ -53,11 +53,6 @@ protected override Compilation GetCompilationForEmit(IEnumerable<string> source,
throw new NotImplementedException();
}
internal override IEnumerable<IModuleSymbol> ReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions = MetadataImportOptions.Public)
{
throw new NotImplementedException();
}
internal override string VisualizeRealIL(IModuleSymbol peModule, CodeAnalysis.CodeGen.CompilationTestData.MethodData methodData, IReadOnlyDictionary<int, string> markers)
{
throw new NotImplementedException();
......
......@@ -38,11 +38,6 @@ public abstract class CSharpTestBase : CSharpTestBaseBase
return (CSharpCompilation)base.GetCompilationForEmit(source, additionalRefs, options, parseOptions);
}
internal new IEnumerable<ModuleSymbol> ReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions = MetadataImportOptions.Public)
{
return base.ReferencesToModuleSymbols(references, importOptions).Cast<ModuleSymbol>();
}
private Action<IModuleSymbol> Translate2(Action<ModuleSymbol> action)
{
if (action != null)
......@@ -219,24 +214,6 @@ public static CSharpCompilation CreateWinRtCompilation(string text, MetadataRefe
TestOptions.ReleaseExe);
}
internal override IEnumerable<IModuleSymbol> ReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions = MetadataImportOptions.Public)
{
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(importOptions);
var tc1 = CSharpCompilation.Create("Dummy", new SyntaxTree[0], references, options);
return references.Select(r =>
{
if (r.Properties.Kind == MetadataImageKind.Assembly)
{
var assemblySymbol = tc1.GetReferencedAssemblySymbol(r);
return (object)assemblySymbol == null ? null : assemblySymbol.Modules[0];
}
else
{
return tc1.GetReferencedModuleSymbol(r);
}
});
}
protected override CompilationOptions CompilationOptionsReleaseDll
{
get { return TestOptions.ReleaseDll; }
......
......@@ -414,20 +414,6 @@ End Class
Public MustInherit Class BasicTestBaseBase
Inherits CommonTestBase
Friend Overrides Function ReferencesToModuleSymbols(references As IEnumerable(Of MetadataReference), Optional importOptions As MetadataImportOptions = MetadataImportOptions.Public) As IEnumerable(Of IModuleSymbol)
Dim options = DirectCast(CompilationOptionsReleaseDll, VisualBasicCompilationOptions).WithMetadataImportOptions(importOptions)
Dim tc1 = VisualBasicCompilation.Create("Dummy", references:=references, options:=options)
Return references.Select(
Function(r)
If r.Properties.Kind = MetadataImageKind.Assembly Then
Dim assemblySymbol = tc1.GetReferencedAssemblySymbol(r)
Return If(assemblySymbol Is Nothing, Nothing, assemblySymbol.Modules(0))
Else
Return tc1.GetReferencedModuleSymbol(r)
End If
End Function)
End Function
Protected Overrides ReadOnly Property CompilationOptionsReleaseDll As CompilationOptions
Get
Return TestOptions.ReleaseDll
......
......@@ -2,6 +2,7 @@
Imports System.IO
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBNamespaceScopes
......@@ -383,7 +384,7 @@ End Class
Dim emitResult1 = c.Emit(peStream:=peStream1, pdbStream:=pdbStream)
Dim emitResult2 = c.Emit(peStream:=peStream2)
PdbValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2)
MetadataValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2)
End Sub
<Fact>
......
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
......
......@@ -491,7 +491,7 @@ End Module
compilation.AssertNoErrors()
' PEVerify should not report "Field value__ ... is not marked RTSpecialName".
Dim verifier = New CompilationVerifier(Me, compilation)
Dim verifier = New CompilationVerifier(compilation)
verifier.EmitAndVerify(
"Error: Field name value__ is reserved for Enums only.")
End Sub
......
......@@ -127,10 +127,6 @@
<Project>{eba4dfa1-6ded-418f-a485-a3b608978906}</Project>
<Name>InteractiveHost</Name>
</ProjectReference>
<ProjectReference Include="..\..\Test\PdbUtilities\PdbUtilities.csproj">
<Project>{afde6bea-5038-4a4a-a88e-dbd2e4088eed}</Project>
<Name>PdbUtilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\Workspaces\Remote\Core\RemoteWorkspaces.csproj">
<Project>{f822f72a-cc87-4e31-b57d-853f65cbebf3}</Project>
<Name>RemoteWorkspaces</Name>
......
......@@ -27,7 +27,6 @@
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
using PDB::Roslyn.Test.MetadataUtilities;
using PDB::Roslyn.Test.PdbUtilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using Microsoft.Metadata.Tools;
namespace Roslyn.Test.MetadataUtilities
{
public static class MethodILExtensions
{
public static unsafe string GetMethodIL(this ImmutableArray<byte> ilArray)
{
var result = new StringBuilder();
fixed (byte* ilPtr = ilArray.ToArray())
{
int offset = 0;
while (true)
{
// skip padding:
while (offset < ilArray.Length && ilArray[offset] == 0)
{
offset++;
}
if (offset == ilArray.Length)
{
break;
}
var reader = new BlobReader(ilPtr + offset, ilArray.Length - offset);
var methodIL = MethodBodyBlock.Create(reader);
if (methodIL == null)
{
result.AppendFormat("<invalid byte 0x{0:X2} at offset {1}>", ilArray[offset], offset);
offset++;
}
else
{
ILVisualizer.Default.DumpMethod(
result,
methodIL.MaxStack,
methodIL.GetILContent(),
ImmutableArray.Create<ILVisualizer.LocalInfo>(),
ImmutableArray.Create<ILVisualizer.HandlerSpan>());
offset += methodIL.Size;
}
}
}
return result.ToString();
}
}
}
......@@ -6,15 +6,23 @@
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.DiaSymReader;
using Roslyn.Test.PdbUtilities;
namespace Roslyn.Test.Utilities
{
internal static class PdbTestUtilities
public static class PdbTestUtilities
{
public static ISymUnmanagedReader3 CreateSymReader(this CompilationVerifier verifier)
{
var pdbStream = new ImmutableMemoryStream(verifier.EmittedAssemblyPdb);
return SymReaderFactory.CreateReader(pdbStream, metadataReaderOpt: null, metadataMemoryOwnerOpt: null);
}
public unsafe static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(this ISymUnmanagedReader3 symReader, MethodDefinitionHandle handle)
{
const int S_OK = 0;
......
......@@ -5,7 +5,6 @@
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
......@@ -14,12 +13,11 @@
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.DiaSymReader;
using Microsoft.DiaSymReader.Tools;
using Microsoft.Metadata.Tools;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
......@@ -29,7 +27,111 @@ namespace Microsoft.CodeAnalysis.Test.Utilities
{
public static class PdbValidation
{
internal static void VerifyPdb(
public static CompilationVerifier VerifyPdb(
this CompilationVerifier verifier,
XElement expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
verifier.Compilation.VerifyPdb(expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return verifier;
}
public static CompilationVerifier VerifyPdb(
this CompilationVerifier verifier,
string expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
verifier.Compilation.VerifyPdb(expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return verifier;
}
public static CompilationVerifier VerifyPdb(
this CompilationVerifier verifier,
string qualifiedMethodName,
string expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
verifier.Compilation.VerifyPdb(qualifiedMethodName, expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return verifier;
}
public static CompilationVerifier VerifyPdb(
this CompilationVerifier verifier,
string qualifiedMethodName,
XElement expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
verifier.Compilation.VerifyPdb(qualifiedMethodName, expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return verifier;
}
public static void VerifyPdb(this CompilationDifference diff, IEnumerable<MethodDefinitionHandle> methodHandles, string expectedPdb)
{
VerifyPdb(diff, methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb);
}
public static void VerifyPdb(this CompilationDifference diff, IEnumerable<MethodDefinitionHandle> methodHandles, XElement expectedPdb)
{
VerifyPdb(diff, methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb);
}
public static void VerifyPdb(
this CompilationDifference diff,
IEnumerable<int> methodTokens,
string expectedPdb,
DebugInformationFormat format = DebugInformationFormat.Pdb,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
VerifyPdb(diff, methodTokens, expectedPdb, format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: false);
}
public static void VerifyPdb(
this CompilationDifference diff,
IEnumerable<int> methodTokens,
XElement expectedPdb,
DebugInformationFormat format = DebugInformationFormat.Pdb,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
VerifyPdb(diff, methodTokens, expectedPdb.ToString(), format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: true);
}
private static void VerifyPdb(
this CompilationDifference diff,
IEnumerable<int> methodTokens,
string expectedPdb,
DebugInformationFormat format,
int expectedValueSourceLine,
string expectedValueSourcePath,
bool expectedIsXmlLiteral)
{
Assert.NotEqual(default(DebugInformationFormat), format);
Assert.NotEqual(DebugInformationFormat.Embedded, format);
string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(diff.PdbDelta), methodTokens);
var (actualXml, expectedXml) = AdjustToPdbFormat(actualPdb, expectedPdb, actualIsPortable: diff.NextGeneration.InitialBaseline.HasPortablePdb);
AssertXml.Equal(expectedXml, actualXml, $"Format: {format}{Environment.NewLine}", expectedValueSourcePath, expectedValueSourceLine, expectedIsXmlLiteral);
}
public static void VerifyPdb(
this Compilation compilation,
string expectedPdb,
IMethodSymbol debugEntryPoint = null,
......@@ -41,7 +143,7 @@ public static class PdbValidation
VerifyPdb(compilation, "", expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
}
internal static void VerifyPdb(
public static void VerifyPdb(
this Compilation compilation,
string qualifiedMethodName,
string expectedPdb,
......@@ -63,7 +165,7 @@ public static class PdbValidation
expectedIsXmlLiteral: false);
}
internal static void VerifyPdb(
public static void VerifyPdb(
this Compilation compilation,
XElement expectedPdb,
IMethodSymbol debugEntryPoint = null,
......@@ -75,7 +177,7 @@ public static class PdbValidation
VerifyPdb(compilation, "", expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
}
internal static void VerifyPdb(
public static void VerifyPdb(
this Compilation compilation,
string qualifiedMethodName,
XElement expectedPdb,
......@@ -406,164 +508,5 @@ private unsafe static void ValidatePortablePdbId(Stream pdbStream, byte[] stampI
Assert.Equal(id.ToArray(), expectedId);
}
}
public static void VerifyMetadataEqualModuloMvid(Stream peStream1, Stream peStream2)
{
peStream1.Position = 0;
peStream2.Position = 0;
var peReader1 = new PEReader(peStream1);
var peReader2 = new PEReader(peStream2);
var md1 = peReader1.GetMetadata().GetContent();
var md2 = peReader2.GetMetadata().GetContent();
var mdReader1 = peReader1.GetMetadataReader();
var mdReader2 = peReader2.GetMetadataReader();
var mvidIndex1 = mdReader1.GetModuleDefinition().Mvid;
var mvidIndex2 = mdReader2.GetModuleDefinition().Mvid;
var mvidOffset1 = mdReader1.GetHeapMetadataOffset(HeapIndex.Guid) + 16 * (MetadataTokens.GetHeapOffset(mvidIndex1) - 1);
var mvidOffset2 = mdReader2.GetHeapMetadataOffset(HeapIndex.Guid) + 16 * (MetadataTokens.GetHeapOffset(mvidIndex2) - 1);
if (!md1.RemoveRange(mvidOffset1, 16).SequenceEqual(md1.RemoveRange(mvidOffset2, 16)))
{
var mdw1 = new StringWriter();
var mdw2 = new StringWriter();
new MetadataVisualizer(mdReader1, mdw1).Visualize();
new MetadataVisualizer(mdReader2, mdw2).Visualize();
mdw1.Flush();
mdw2.Flush();
AssertEx.AssertResultsEqual(mdw1.ToString(), mdw2.ToString());
}
}
public static Dictionary<int, string> GetMarkers(string pdbXml, string source = null)
{
string[] lines = source?.Split(new[] { "\r\n" }, StringSplitOptions.None);
var doc = new XmlDocument();
doc.LoadXml(pdbXml);
var result = new Dictionary<int, string>();
if (source == null)
{
foreach (XmlNode entry in doc.GetElementsByTagName("sequencePoints"))
{
foreach (XmlElement item in entry.ChildNodes)
{
Add(result,
Convert.ToInt32(item.GetAttribute("offset"), 16),
(item.GetAttribute("hidden") == "true") ? "~" : "-");
}
}
foreach (XmlNode entry in doc.GetElementsByTagName("asyncInfo"))
{
foreach (XmlElement item in entry.ChildNodes)
{
if (item.Name == "await")
{
Add(result, Convert.ToInt32(item.GetAttribute("yield"), 16), "<");
Add(result, Convert.ToInt32(item.GetAttribute("resume"), 16), ">");
}
else if (item.Name == "catchHandler")
{
Add(result, Convert.ToInt32(item.GetAttribute("offset"), 16), "$");
}
}
}
}
else
{
foreach (XmlNode entry in doc.GetElementsByTagName("asyncInfo"))
{
foreach (XmlElement item in entry.ChildNodes)
{
if (item.Name == "await")
{
AddTextual(result, Convert.ToInt32(item.GetAttribute("yield"), 16), "async: yield");
AddTextual(result, Convert.ToInt32(item.GetAttribute("resume"), 16), "async: resume");
}
else if (item.Name == "catchHandler")
{
AddTextual(result, Convert.ToInt32(item.GetAttribute("offset"), 16), "async: catch handler");
}
}
}
foreach (XmlNode entry in doc.GetElementsByTagName("sequencePoints"))
{
foreach (XmlElement item in entry.ChildNodes)
{
AddTextual(result, Convert.ToInt32(item.GetAttribute("offset"), 16), "sequence point: " + SnippetFromSpan(lines, item));
}
}
}
return result;
void Add(Dictionary<int, string> dict, int key, string value)
{
if (dict.TryGetValue(key, out string found))
{
dict[key] = found + value;
}
else
{
dict[key] = value;
}
}
void AddTextual(Dictionary<int, string> dict, int key, string value)
{
if (dict.TryGetValue(key, out string found))
{
dict[key] = found + ", " + value;
}
else
{
dict[key] = "// " + value;
}
}
}
private static string SnippetFromSpan(string[] lines, XmlElement span)
{
if (span.GetAttribute("hidden") != "true")
{
var startLine = Convert.ToInt32(span.GetAttribute("startLine"));
var startColumn = Convert.ToInt32(span.GetAttribute("startColumn"));
var endLine = Convert.ToInt32(span.GetAttribute("endLine"));
var endColumn = Convert.ToInt32(span.GetAttribute("endColumn"));
if (startLine == endLine)
{
return lines[startLine - 1].Substring(startColumn - 1, endColumn - startColumn);
}
else
{
var start = lines[startLine - 1].Substring(startColumn - 1);
var end = lines[endLine - 1].Substring(0, endColumn - 1);
return TruncateStart(start, 12) + " ... " + TruncateEnd(end, 12);
}
}
else
{
return "<hidden>";
}
string TruncateStart(string text, int maxLength)
{
if (text.Length < maxLength) { return text; }
return text.Substring(0, maxLength);
}
string TruncateEnd(string text, int maxLength)
{
if (text.Length < maxLength) { return text; }
return text.Substring(text.Length - maxLength - 1, maxLength);
}
}
}
}
......@@ -11,6 +11,7 @@
<RootNamespace>Roslyn.Test.PdbUtilities</RootNamespace>
<AssemblyName>Roslyn.Test.PdbUtilities</AssemblyName>
<TargetFramework>netstandard1.3</TargetFramework>
<PackageTargetFallback>portable-net452</PackageTargetFallback>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
......@@ -18,18 +19,10 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'" />
<ItemGroup Label="Linked Files">
<Compile Include="..\..\Compilers\Core\Portable\InternalUtilities\ExceptionUtilities.cs">
<Link>InternalUtilities\ExceptionUtilities.cs</Link>
</Compile>
<Compile Include="..\..\Compilers\Core\Portable\InternalUtilities\Hash.cs">
<Link>InternalUtilities\Hash.cs</Link>
</Compile>
<Compile Include="..\..\Compilers\Core\Portable\InternalUtilities\StreamExtensions.cs">
<Link>InternalUtilities\StreamExtensions.cs</Link>
</Compile>
<Compile Include="Metadata\AggregatedMetadataReader.cs" />
<Compile Include="Metadata\MethodILExtensions.cs" />
<Compile Include="Pdb\CustomDebugInfoUtilities.cs" />
<Compile Include="Pdb\MockSymWriter.cs" />
<Compile Include="Pdb\PdbTestUtilities.cs" />
<Compile Include="Pdb\PdbValidation.cs" />
<Compile Include="Pdb\SymReaderFactory.cs" />
<Compile Include="Pdb\Token2SourceLineExporter.cs" />
<Compile Include="Shared\DateTimeUtilities.cs" />
......@@ -37,20 +30,52 @@
<Compile Include="Shared\StringUtilities.cs" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.CommandLine.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Emit.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.WinRT.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.PerformanceTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Semantic.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Symbol.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Syntax.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Test.Utilities" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Test.Utilities.Desktop" />
<InternalsVisibleToTest Include="Roslyn.Compilers.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.CommandLine.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.Emit.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.EnC.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.PerformanceTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.Semantic.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.Symbol.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.Syntax.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.VisualBasic.Test.Utilities" />
<InternalsVisibleToTest Include="Roslyn.ExpressionEvaluator.CSharp.ExpressionCompiler.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.ExpressionEvaluator.CSharp.ResultProvider.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.ExpressionEvaluator.ExpressionCompiler.Test.Utilities" />
<InternalsVisibleToTest Include="Roslyn.ExpressionEvaluator.FunctionResolver.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.ExpressionEvaluator.VisualBasic.ExpressionCompiler.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.ExpressionEvaluator.VisualBasic.ResultProvider.UnitTests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DiaSymReader.Native" Version="$(MicrosoftDiaSymReaderNativeVersion)" />
<PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" />
<PackageReference Include="Microsoft.DiaSymReader.PortablePdb" Version="$(MicrosoftDiaSymReaderPortablePdbVersion)" />
<PackageReference Include="Microsoft.DiaSymReader.Converter.Xml" Version="$(MicrosoftDiaSymReaderConverterXmlVersion)" />
<PackageReference Include="Microsoft.Metadata.Visualizer" Version="$(MicrosoftMetadataVisualizerVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" />
<PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" />
<PackageReference Include="System.Xml.ReaderWriter" Version="$(SystemXmlReaderWriterVersion)" />
<PackageReference Include="System.ValueTuple" Version="$(SystemValueTupleVersion)" />
<PackageReference Include="xunit.assert" Version="$(xunitassertVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}</Project>
<Name>CodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\Utilities\Portable\TestUtilities.csproj">
<Project>{ccbd3438-3e84-40a9-83ad-533f23bcfca5}</Project>
<Name>TestUtilities</Name>
</ProjectReference>
</ItemGroup>
<Import Project="..\..\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems" Label="Shared" />
<Import Project="..\..\Dependencies\CodeAnalysis.Metadata\Microsoft.CodeAnalysis.Metadata.projitems" Label="Shared" />
<Import Project="..\..\..\build\Targets\Imports.targets" />
</Project>
\ No newline at end of file
......@@ -32,6 +32,7 @@
<Compile Include="Logger.cs" />
<Compile Include="PerfTestBase.cs" />
<Compile Include="RelativeDirectory.cs" />
<Compile Include="VsPerfTest.cs" />
<Compile Include="ScenarioGenerator.cs" />
<Compile Include="TestUtilities.cs" />
<Compile Include="TraceManager.cs" />
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using static Roslyn.Test.Performance.Utilities.TestUtilities;
namespace Roslyn.Test.Performance.Utilities
{
public abstract class VsPerfTest : PerfTest
{
private static readonly string _rootSuffix = "RoslynPerf";
private readonly ILogger _logger;
private readonly string _testTemplateName;
private readonly string _testName;
private readonly string _zipFileToDownload;
private readonly int _zipFileVersion;
private readonly string _solutionToTest;
private readonly string _benchviewUploadName;
private readonly string[] _scenarios;
private static readonly string _nugetPackagesPath = System.Environment.GetEnvironmentVariable("NUGET_PACKAGES") ??
Path.Combine(System.Environment.GetEnvironmentVariable("UserProfile"), ".nuget", "packages");
private static readonly string _installerPath = Path.Combine(_nugetPackagesPath, "roslyntools.microsoft.vsixexpinstaller", "0.2.4-beta", "tools", "vsixexpinstaller.exe");
public VsPerfTest(
string testTemplateName,
string testName,
string solutionToTest,
string benchviewUploadName,
string[] scenarios,
string zipFileToDownload = "RoslynSolutions",
int zipFileVersion = 2) : base()
{
_testTemplateName = testTemplateName;
_testName = testName;
_zipFileToDownload = zipFileToDownload;
_zipFileVersion = zipFileVersion;
_solutionToTest = solutionToTest;
_benchviewUploadName = benchviewUploadName;
_scenarios = scenarios;
_logger = new ConsoleAndFileLogger();
}
public override void Setup()
{
// Download test zip
var dir = Path.Combine(Path.GetDirectoryName(MyWorkingDirectory), "csharp");
DownloadProject(_zipFileToDownload, version: _zipFileVersion, logger: _logger);
// Create log directory
var logDirectory = Path.Combine(TempDirectory, _testName);
Directory.CreateDirectory(logDirectory);
Directory.CreateDirectory(Path.Combine(logDirectory, "PerfResults"));
// Read the test template and replace with actual solution path.
var taoTestFileTemplatePath = Path.Combine(dir, _testTemplateName);
var template = File.ReadAllText(taoTestFileTemplatePath);
var finalTest = template.Replace("ReplaceWithActualSolutionPath", Path.Combine(TempDirectory, _zipFileToDownload, _solutionToTest));
finalTest = finalTest.Replace("ReplaceWithPerfLogDirectory", logDirectory);
// Perform test specific string replacements
finalTest = GetFinalTestSource(finalTest, dir);
// Write the final test into the test file.
File.WriteAllText(Path.Combine(TempDirectory, _testTemplateName), finalTest);
// Install Roslyn VSIXes into the perf hive.
InstallVsixes();
}
protected virtual string GetFinalTestSource(string testTemplateWithReplacedSolutionPath, string testFolderDirectory)
=> testTemplateWithReplacedSolutionPath;
protected void InstallVsixes()
{
var vsix1 = Path.Combine(MyBinaries(), "Vsix", "VisualStudioSetup", "Roslyn.VisualStudio.Setup.vsix");
var vsix2 = Path.Combine(MyBinaries(), "Vsix", "VisualStudioSetup.Next", "Roslyn.VisualStudio.Setup.Next.vsix");
var rootSuffixArg = $"/rootsuffix:{_rootSuffix}";
// First uninstall any vsixes in the hive
ShellOutVital(_installerPath, $"{rootSuffixArg}, /uninstallAll");
// Then install the RoslynDeployment.vsix we just built
ShellOutVital(_installerPath, $"{rootSuffixArg} {vsix1}");
ShellOutVital(_installerPath, $"{rootSuffixArg} {vsix2}");
}
public override void Test()
{
var args = $"{Path.Combine(TempDirectory, _testTemplateName)} -perf -host:vs -roslynonly -rootsuffix:{_rootSuffix}";
ShellOutVital(TaoPath, args, TempDirectory);
var logDirectory = Path.Combine(TempDirectory, _testName, "PerfResults");
var xcopyArgs = $"{logDirectory} {Path.Combine(MyBinaries(), "..", "..", "ToArchive")} /s /i /y";
ShellOutVital("xcopy", xcopyArgs);
foreach (var xml in Directory.EnumerateFiles(logDirectory, "*.xml"))
{
Benchview.UploadBenchviewReport(xml, _benchviewUploadName);
}
_logger.Flush();
}
public override int Iterations => 1;
public override string Name => _testTemplateName.Substring(0, _testTemplateName.IndexOf("Template.xml"));
public override string MeasuredProc => "devenv";
public override bool ProvidesScenarios => false;
public override string[] GetScenarios()
{
throw new System.NotImplementedException();
}
public override ITraceManager GetTraceManager()
{
return TraceManagerFactory.NoOpTraceManager();
}
}
}
\ No newline at end of file
......@@ -22,10 +22,6 @@
<Project>{7fe6b002-89d8-4298-9b1b-0b5c247dd1fd}</Project>
<Name>CompilerTestResources</Name>
</ProjectReference>
<ProjectReference Include="..\..\PdbUtilities\PdbUtilities.csproj">
<Project>{afde6bea-5038-4a4a-a88e-dbd2e4088eed}</Project>
<Name>PdbUtilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}</Project>
<Name>CodeAnalysis</Name>
......
......@@ -31,10 +31,6 @@
<Project>{2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}</Project>
<Name>BasicCodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\PdbUtilities\PdbUtilities.csproj">
<Project>{afde6bea-5038-4a4a-a88e-dbd2e4088eed}</Project>
<Name>PdbUtilities</Name>
</ProjectReference>
<ProjectReference Include="..\Portable\TestUtilities.csproj">
<Project>{ccbd3438-3e84-40a9-83ad-533f23bcfca5}</Project>
<Name>TestUtilities</Name>
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.DiaSymReader;
using Microsoft.DiaSymReader.Tools;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public partial class CommonTestBase
{
public class CompilationVerifier
{
private readonly CommonTestBase _test;
private readonly Compilation _compilation;
private CompilationTestData _testData;
private readonly IEnumerable<ModuleData> _dependencies;
private ImmutableArray<Diagnostic> _diagnostics;
private IModuleSymbol _lazyModuleSymbol;
private IList<ModuleData> _allModuleData;
internal ImmutableArray<byte> EmittedAssemblyData;
internal ImmutableArray<byte> EmittedAssemblyPdb;
public CompilationVerifier(
CommonTestBase test,
Compilation compilation,
IEnumerable<ModuleData> dependencies = null)
{
_test = test;
_compilation = compilation;
_dependencies = dependencies;
}
internal CompilationTestData TestData
{
get { return _testData; }
}
public Compilation Compilation
{
get { return _compilation; }
}
public TempRoot Temp
{
get { return _test.Temp; }
}
internal ImmutableArray<Diagnostic> Diagnostics
{
get { return _diagnostics; }
}
internal ImmutableArray<ModuleMetadata> GetAllModuleMetadata()
{
if (EmittedAssemblyData == null)
{
throw new InvalidOperationException("You must call Emit before calling GetAllModuleMetadata.");
}
ImmutableArray<ModuleMetadata> modules = ImmutableArray.Create(ModuleMetadata.CreateFromImage(EmittedAssemblyData));
if (_allModuleData != null)
{
var netModules = _allModuleData.Where(m => m.Kind == OutputKind.NetModule);
if (netModules.Any())
{
modules = modules.Concat(
ImmutableArray.CreateRange(netModules.Select(m => ModuleMetadata.CreateFromImage(m.Image))));
}
}
return modules;
}
public void Emit(string expectedOutput, int? expectedReturnCode, string[] args, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, bool peVerify, SignatureDescription[] expectedSignatures)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleName = Emit(testEnvironment, manifestResources, emitOptions);
_allModuleData = testEnvironment.GetAllModuleData();
if (peVerify)
{
testEnvironment.PeVerify();
}
if (expectedSignatures != null)
{
MetadataSignatureUnitTestHelper.VerifyMemberSignatures(testEnvironment, expectedSignatures);
}
if (expectedOutput != null || expectedReturnCode != null)
{
var returnCode = testEnvironment.Execute(mainModuleName, args, expectedOutput);
if (expectedReturnCode is int exCode)
{
Assert.Equal(exCode, returnCode);
}
}
}
}
// TODO(tomat): Fold into CompileAndVerify.
// Replace bool verify parameter with string[] expectedPeVerifyOutput. If null, no verification. If empty verify have to succeed. Otherwise compare errors.
public void EmitAndVerify(params string[] expectedPeVerifyOutput)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleName = Emit(testEnvironment, null, null);
string[] actualOutput = testEnvironment.PeVerifyModules(new[] { mainModuleName }, throwOnError: false);
Assert.Equal(expectedPeVerifyOutput, actualOutput);
}
}
private string Emit(IRuntimeEnvironment testEnvironment, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions)
{
testEnvironment.Emit(_compilation, manifestResources, emitOptions);
_diagnostics = testEnvironment.GetDiagnostics();
EmittedAssemblyData = testEnvironment.GetMainImage();
EmittedAssemblyPdb = testEnvironment.GetMainPdb();
_testData = ((IInternalRuntimeEnvironment)testEnvironment).GetCompilationTestData();
return _compilation.Assembly.Identity.GetDisplayName();
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
XCData expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath]string callerPath = null,
[CallerLineNumber]int callerLine = 0)
{
return VerifyILImpl(qualifiedMethodName, expectedIL.Value, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: false);
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
string expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath]string callerPath = null,
[CallerLineNumber]int callerLine = 0,
string source = null)
{
return VerifyILImpl(qualifiedMethodName, expectedIL, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: true, source: source);
}
public void VerifyLocalSignature(
string qualifiedMethodName,
string expectedSignature,
[CallerLineNumber]int callerLine = 0,
[CallerFilePath]string callerPath = null)
{
var ilBuilder = _testData.GetMethodData(qualifiedMethodName).ILBuilder;
string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
private CompilationVerifier VerifyILImpl(
string qualifiedMethodName,
string expectedIL,
bool realIL,
string sequencePoints,
string callerPath,
int callerLine,
bool escapeQuotes,
string source = null)
{
string actualIL = VisualizeIL(qualifiedMethodName, realIL, sequencePoints, source);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes, callerPath, callerLine);
return this;
}
public CompilationVerifier VerifyPdb(
XElement expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
_compilation.VerifyPdb(expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return this;
}
public CompilationVerifier VerifyPdb(
string expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
_compilation.VerifyPdb(expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return this;
}
public CompilationVerifier VerifyPdb(
string qualifiedMethodName,
string expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
_compilation.VerifyPdb(qualifiedMethodName, expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return this;
}
public CompilationVerifier VerifyPdb(
string qualifiedMethodName,
XElement expectedPdb,
IMethodSymbol debugEntryPoint = null,
DebugInformationFormat format = 0,
PdbToXmlOptions options = 0,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
_compilation.VerifyPdb(qualifiedMethodName, expectedPdb, debugEntryPoint, format, options, expectedValueSourceLine, expectedValueSourcePath);
return this;
}
public ISymUnmanagedReader3 CreateSymReader()
{
var pdbStream = new MemoryStream(EmittedAssemblyPdb.ToArray());
return SymReaderFactory.CreateReader(pdbStream, metadataReaderOpt: null, metadataMemoryOwnerOpt: null);
}
public string VisualizeIL(string qualifiedMethodName, bool realIL = false, string sequencePoints = null, string source = null)
{
// TODO: Currently the qualifiedMethodName is a symbol display name while PDB need metadata name.
// So we need to pass the PDB metadata name of the method to sequencePoints (instead of just bool).
return VisualizeIL(_testData.GetMethodData(qualifiedMethodName), realIL, sequencePoints, source);
}
internal string VisualizeIL(CompilationTestData.MethodData methodData, bool realIL, string sequencePoints = null, string source = null)
{
Dictionary<int, string> markers = null;
if (sequencePoints != null)
{
var actualPdbXml = PdbToXmlConverter.ToXml(
pdbStream: new MemoryStream(EmittedAssemblyPdb.ToArray()),
peStream: new MemoryStream(EmittedAssemblyData.ToArray()),
options: PdbToXmlOptions.ResolveTokens |
PdbToXmlOptions.ThrowOnError |
PdbToXmlOptions.ExcludeDocuments |
PdbToXmlOptions.ExcludeCustomDebugInformation |
PdbToXmlOptions.ExcludeScopes,
methodName: sequencePoints);
markers = PdbValidation.GetMarkers(actualPdbXml, source);
}
if (!realIL)
{
return ILBuilderVisualizer.ILBuilderToString(methodData.ILBuilder, markers: markers);
}
if (_lazyModuleSymbol == null)
{
_lazyModuleSymbol = GetModuleSymbolForEmittedImage(EmittedAssemblyData, MetadataImportOptions.All);
}
return _lazyModuleSymbol != null ? _test.VisualizeRealIL(_lazyModuleSymbol, methodData, markers) : null;
}
public CompilationVerifier VerifyMemberInIL(string methodName, bool expected)
{
Assert.Equal(expected, _testData.GetMethodsByName().ContainsKey(methodName));
return this;
}
public CompilationVerifier VerifyDiagnostics(params DiagnosticDescription[] expected)
{
_diagnostics.Verify(expected);
return this;
}
public IModuleSymbol GetModuleSymbolForEmittedImage()
{
return GetModuleSymbolForEmittedImage(EmittedAssemblyData, _compilation.Options.MetadataImportOptions);
}
private IModuleSymbol GetModuleSymbolForEmittedImage(ImmutableArray<byte> peImage, MetadataImportOptions importOptions)
{
if (peImage.IsDefault)
{
return null;
}
var targetReference = LoadTestEmittedExecutableForSymbolValidation(peImage, _compilation.Options.OutputKind, display: _compilation.AssemblyName);
var references = _compilation.References.Concat(new[] { targetReference });
var assemblies = _test.ReferencesToModuleSymbols(references, importOptions);
return assemblies.Last();
}
internal static MetadataReference LoadTestEmittedExecutableForSymbolValidation(
ImmutableArray<byte> image,
OutputKind outputKind,
string display = null)
{
var moduleMetadata = ModuleMetadata.CreateFromImage(image);
moduleMetadata.Module.PretendThereArentNoPiaLocalTypes();
if (outputKind == OutputKind.NetModule)
{
return moduleMetadata.GetReference(display: display);
}
else
{
return AssemblyMetadata.Create(moduleMetadata).GetReference(display: display);
}
}
public void VerifyOperationTree(string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
public void VerifyOperationTree(string symbolToVerify, string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(symbolToVerify, expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
}
}
}
......@@ -23,8 +23,6 @@ namespace Microsoft.CodeAnalysis.Test.Utilities
/// </summary>
public abstract partial class CommonTestBase : TestBase
{
internal abstract IEnumerable<IModuleSymbol> ReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions = MetadataImportOptions.Public);
#region Emit
protected abstract Compilation GetCompilationForEmit(
......@@ -214,9 +212,7 @@ static internal void RunValidators(CompilationVerifier verifier, Action<PEAssemb
EmitOptions emitOptions,
bool verify)
{
CompilationVerifier verifier = null;
verifier = new CompilationVerifier(this, compilation, dependencies);
var verifier = new CompilationVerifier(compilation, VisualizeRealIL, dependencies);
verifier.Emit(expectedOutput, expectedReturnCode, args, manifestResources, emitOptions, verify, expectedSignatures);
......
......@@ -3,35 +3,29 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.DiaSymReader.Tools;
using Microsoft.Metadata.Tools;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
internal sealed class CompilationDifference
public sealed class CompilationDifference
{
public readonly ImmutableArray<byte> MetadataDelta;
public readonly ImmutableArray<byte> ILDelta;
public readonly ImmutableArray<byte> PdbDelta;
public readonly CompilationTestData TestData;
internal readonly CompilationTestData TestData;
public readonly EmitDifferenceResult EmitResult;
public readonly ImmutableArray<MethodDefinitionHandle> UpdatedMethods;
public CompilationDifference(
internal CompilationDifference(
ImmutableArray<byte> metadata,
ImmutableArray<byte> il,
ImmutableArray<byte> pdb,
......@@ -55,7 +49,7 @@ public EmitBaseline NextGeneration
}
}
public PinnedMetadata GetMetadata()
internal PinnedMetadata GetMetadata()
{
return new PinnedMetadata(MetadataDelta);
}
......@@ -80,7 +74,7 @@ public PinnedMetadata GetMetadata()
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
public void VerifyIL(
internal void VerifyIL(
string qualifiedMethodName,
string expectedIL,
Func<Cci.ILocalDefinition, ILVisualizer.LocalInfo> mapLocal = null,
......@@ -94,60 +88,13 @@ public PinnedMetadata GetMetadata()
if (!methodToken.IsNil)
{
string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(PdbDelta), new[] { MetadataTokens.GetToken(methodToken) });
sequencePointMarkers = PdbValidation.GetMarkers(actualPdb);
sequencePointMarkers = ILValidation.GetSequencePointMarkers(actualPdb);
}
string actualIL = ILBuilderVisualizer.ILBuilderToString(ilBuilder, mapLocal ?? ToLocalInfo, sequencePointMarkers);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
public void VerifyPdb(IEnumerable<MethodDefinitionHandle> methodHandles, string expectedPdb)
{
VerifyPdb(methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb);
}
public void VerifyPdb(IEnumerable<MethodDefinitionHandle> methodHandles, XElement expectedPdb)
{
VerifyPdb(methodHandles.Select(h => MetadataTokens.GetToken(h)), expectedPdb);
}
public void VerifyPdb(
IEnumerable<int> methodTokens,
string expectedPdb,
DebugInformationFormat format = DebugInformationFormat.Pdb,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
VerifyPdb(methodTokens, expectedPdb, format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: false);
}
public void VerifyPdb(
IEnumerable<int> methodTokens,
XElement expectedPdb,
DebugInformationFormat format = DebugInformationFormat.Pdb,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
VerifyPdb(methodTokens, expectedPdb.ToString(), format, expectedValueSourceLine, expectedValueSourcePath, expectedIsXmlLiteral: true);
}
private void VerifyPdb(
IEnumerable<int> methodTokens,
string expectedPdb,
DebugInformationFormat format,
int expectedValueSourceLine,
string expectedValueSourcePath,
bool expectedIsXmlLiteral)
{
Assert.NotEqual(default(DebugInformationFormat), format);
Assert.NotEqual(DebugInformationFormat.Embedded, format);
string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(PdbDelta), methodTokens);
var (actualXml, expectedXml) = PdbValidation.AdjustToPdbFormat(actualPdb, expectedPdb, actualIsPortable: NextGeneration.InitialBaseline.HasPortablePdb);
AssertXml.Equal(expectedXml, actualXml, $"Format: {format}{Environment.NewLine}", expectedValueSourcePath, expectedValueSourceLine, expectedIsXmlLiteral);
}
internal string GetMethodIL(string qualifiedMethodName)
{
return ILBuilderVisualizer.ILBuilderToString(this.TestData.GetMethodData(qualifiedMethodName).ILBuilder, ToLocalInfo);
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.DiaSymReader.Tools;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class CompilationVerifier
{
private readonly Compilation _compilation;
private CompilationTestData _testData;
private readonly IEnumerable<ModuleData> _dependencies;
private ImmutableArray<Diagnostic> _diagnostics;
private IModuleSymbol _lazyModuleSymbol;
private IList<ModuleData> _allModuleData;
public ImmutableArray<byte> EmittedAssemblyData;
public ImmutableArray<byte> EmittedAssemblyPdb;
private readonly Func<IModuleSymbol, CompilationTestData.MethodData, IReadOnlyDictionary<int, string>, string> _visualizeRealIL;
internal CompilationVerifier(
Compilation compilation,
Func<IModuleSymbol, CompilationTestData.MethodData, IReadOnlyDictionary<int, string>, string> visualizeRealIL = null,
IEnumerable<ModuleData> dependencies = null)
{
_compilation = compilation;
_dependencies = dependencies;
_visualizeRealIL = visualizeRealIL;
}
internal CompilationTestData TestData => _testData;
public Compilation Compilation => _compilation;
internal ImmutableArray<Diagnostic> Diagnostics => _diagnostics;
internal ImmutableArray<ModuleMetadata> GetAllModuleMetadata()
{
if (EmittedAssemblyData == null)
{
throw new InvalidOperationException("You must call Emit before calling GetAllModuleMetadata.");
}
ImmutableArray<ModuleMetadata> modules = ImmutableArray.Create(ModuleMetadata.CreateFromImage(EmittedAssemblyData));
if (_allModuleData != null)
{
var netModules = _allModuleData.Where(m => m.Kind == OutputKind.NetModule);
if (netModules.Any())
{
modules = modules.Concat(
ImmutableArray.CreateRange(netModules.Select(m => ModuleMetadata.CreateFromImage(m.Image))));
}
}
return modules;
}
public void Emit(string expectedOutput, int? expectedReturnCode, string[] args, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, bool peVerify, SignatureDescription[] expectedSignatures)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleName = Emit(testEnvironment, manifestResources, emitOptions);
_allModuleData = testEnvironment.GetAllModuleData();
if (peVerify)
{
testEnvironment.PeVerify();
}
if (expectedSignatures != null)
{
MetadataSignatureUnitTestHelper.VerifyMemberSignatures(testEnvironment, expectedSignatures);
}
if (expectedOutput != null || expectedReturnCode != null)
{
var returnCode = testEnvironment.Execute(mainModuleName, args, expectedOutput);
if (expectedReturnCode is int exCode)
{
Assert.Equal(exCode, returnCode);
}
}
}
}
// TODO(tomat): Fold into CompileAndVerify.
// Replace bool verify parameter with string[] expectedPeVerifyOutput. If null, no verification. If empty verify have to succeed. Otherwise compare errors.
public void EmitAndVerify(params string[] expectedPeVerifyOutput)
{
using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies))
{
string mainModuleName = Emit(testEnvironment, null, null);
string[] actualOutput = testEnvironment.PeVerifyModules(new[] { mainModuleName }, throwOnError: false);
Assert.Equal(expectedPeVerifyOutput, actualOutput);
}
}
private string Emit(IRuntimeEnvironment testEnvironment, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions)
{
testEnvironment.Emit(_compilation, manifestResources, emitOptions);
_diagnostics = testEnvironment.GetDiagnostics();
EmittedAssemblyData = testEnvironment.GetMainImage();
EmittedAssemblyPdb = testEnvironment.GetMainPdb();
_testData = ((IInternalRuntimeEnvironment)testEnvironment).GetCompilationTestData();
return _compilation.Assembly.Identity.GetDisplayName();
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
XCData expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath]string callerPath = null,
[CallerLineNumber]int callerLine = 0)
{
return VerifyILImpl(qualifiedMethodName, expectedIL.Value, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: false);
}
public CompilationVerifier VerifyIL(
string qualifiedMethodName,
string expectedIL,
bool realIL = false,
string sequencePoints = null,
[CallerFilePath]string callerPath = null,
[CallerLineNumber]int callerLine = 0,
string source = null)
{
return VerifyILImpl(qualifiedMethodName, expectedIL, realIL, sequencePoints, callerPath, callerLine, escapeQuotes: true, source: source);
}
public void VerifyLocalSignature(
string qualifiedMethodName,
string expectedSignature,
[CallerLineNumber]int callerLine = 0,
[CallerFilePath]string callerPath = null)
{
var ilBuilder = _testData.GetMethodData(qualifiedMethodName).ILBuilder;
string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
private CompilationVerifier VerifyILImpl(
string qualifiedMethodName,
string expectedIL,
bool realIL,
string sequencePoints,
string callerPath,
int callerLine,
bool escapeQuotes,
string source = null)
{
string actualIL = VisualizeIL(qualifiedMethodName, realIL, sequencePoints, source);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes, callerPath, callerLine);
return this;
}
public string VisualizeIL(string qualifiedMethodName, bool realIL = false, string sequencePoints = null, string source = null)
{
// TODO: Currently the qualifiedMethodName is a symbol display name while PDB need metadata name.
// So we need to pass the PDB metadata name of the method to sequencePoints (instead of just bool).
return VisualizeIL(_testData.GetMethodData(qualifiedMethodName), realIL, sequencePoints, source);
}
internal string VisualizeIL(CompilationTestData.MethodData methodData, bool realIL, string sequencePoints = null, string source = null)
{
Dictionary<int, string> markers = null;
if (sequencePoints != null)
{
var actualPdbXml = PdbToXmlConverter.ToXml(
pdbStream: new MemoryStream(EmittedAssemblyPdb.ToArray()),
peStream: new MemoryStream(EmittedAssemblyData.ToArray()),
options: PdbToXmlOptions.ResolveTokens |
PdbToXmlOptions.ThrowOnError |
PdbToXmlOptions.ExcludeDocuments |
PdbToXmlOptions.ExcludeCustomDebugInformation |
PdbToXmlOptions.ExcludeScopes,
methodName: sequencePoints);
markers = ILValidation.GetSequencePointMarkers(actualPdbXml, source);
}
if (!realIL)
{
return ILBuilderVisualizer.ILBuilderToString(methodData.ILBuilder, markers: markers);
}
if (_lazyModuleSymbol == null)
{
_lazyModuleSymbol = GetModuleSymbolForEmittedImage(EmittedAssemblyData, MetadataImportOptions.All);
}
return _lazyModuleSymbol != null ? _visualizeRealIL(_lazyModuleSymbol, methodData, markers) : null;
}
public CompilationVerifier VerifyMemberInIL(string methodName, bool expected)
{
Assert.Equal(expected, _testData.GetMethodsByName().ContainsKey(methodName));
return this;
}
public CompilationVerifier VerifyDiagnostics(params DiagnosticDescription[] expected)
{
_diagnostics.Verify(expected);
return this;
}
public IModuleSymbol GetModuleSymbolForEmittedImage()
{
return GetModuleSymbolForEmittedImage(EmittedAssemblyData, _compilation.Options.MetadataImportOptions);
}
private IModuleSymbol GetModuleSymbolForEmittedImage(ImmutableArray<byte> peImage, MetadataImportOptions importOptions)
{
if (peImage.IsDefault)
{
return null;
}
var targetReference = LoadTestEmittedExecutableForSymbolValidation(peImage, _compilation.Options.OutputKind, display: _compilation.AssemblyName);
var references = _compilation.References.Concat(new[] { targetReference });
var assemblies = GetReferencesToModuleSymbols(references, importOptions);
return assemblies.Last();
}
private IEnumerable<IModuleSymbol> GetReferencesToModuleSymbols(IEnumerable<MetadataReference> references, MetadataImportOptions importOptions)
{
var dummy = _compilation
.RemoveAllSyntaxTrees()
.WithReferences(references)
.WithAssemblyName("Dummy")
.WithOptions(_compilation.Options.WithMetadataImportOptions(importOptions));
return references.Select(reference =>
{
if (reference.Properties.Kind == MetadataImageKind.Assembly)
{
return ((IAssemblySymbol)dummy.GetAssemblyOrModuleSymbol(reference))?.Modules.First();
}
else
{
return (IModuleSymbol)dummy.GetAssemblyOrModuleSymbol(reference);
}
});
}
internal static MetadataReference LoadTestEmittedExecutableForSymbolValidation(
ImmutableArray<byte> image,
OutputKind outputKind,
string display = null)
{
var moduleMetadata = ModuleMetadata.CreateFromImage(image);
moduleMetadata.Module.PretendThereArentNoPiaLocalTypes();
if (outputKind == OutputKind.NetModule)
{
return moduleMetadata.GetReference(display: display);
}
else
{
return AssemblyMetadata.Create(moduleMetadata).GetReference(display: display);
}
}
public void VerifyOperationTree(string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
public void VerifyOperationTree(string symbolToVerify, string expectedOperationTree, bool skipImplicitlyDeclaredSymbols = false)
{
_compilation.VerifyOperationTree(symbolToVerify, expectedOperationTree, skipImplicitlyDeclaredSymbols);
}
}
}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Xml;
using Microsoft.Metadata.Tools;
namespace Roslyn.Test.Utilities
{
public static class ILValidation
{
public static unsafe string GetMethodIL(this ImmutableArray<byte> ilArray)
{
var result = new StringBuilder();
fixed (byte* ilPtr = ilArray.ToArray())
{
int offset = 0;
while (true)
{
// skip padding:
while (offset < ilArray.Length && ilArray[offset] == 0)
{
offset++;
}
if (offset == ilArray.Length)
{
break;
}
var reader = new BlobReader(ilPtr + offset, ilArray.Length - offset);
var methodIL = MethodBodyBlock.Create(reader);
if (methodIL == null)
{
result.AppendFormat("<invalid byte 0x{0:X2} at offset {1}>", ilArray[offset], offset);
offset++;
}
else
{
ILVisualizer.Default.DumpMethod(
result,
methodIL.MaxStack,
methodIL.GetILContent(),
ImmutableArray.Create<ILVisualizer.LocalInfo>(),
ImmutableArray.Create<ILVisualizer.HandlerSpan>());
offset += methodIL.Size;
}
}
}
return result.ToString();
}
public static Dictionary<int, string> GetSequencePointMarkers(string pdbXml, string source = null)
{
string[] lines = source?.Split(new[] { "\r\n" }, StringSplitOptions.None);
var doc = new XmlDocument();
doc.LoadXml(pdbXml);
var result = new Dictionary<int, string>();
if (source == null)
{
foreach (XmlNode entry in doc.GetElementsByTagName("sequencePoints"))
{
foreach (XmlElement item in entry.ChildNodes)
{
Add(result,
Convert.ToInt32(item.GetAttribute("offset"), 16),
(item.GetAttribute("hidden") == "true") ? "~" : "-");
}
}
foreach (XmlNode entry in doc.GetElementsByTagName("asyncInfo"))
{
foreach (XmlElement item in entry.ChildNodes)
{
if (item.Name == "await")
{
Add(result, Convert.ToInt32(item.GetAttribute("yield"), 16), "<");
Add(result, Convert.ToInt32(item.GetAttribute("resume"), 16), ">");
}
else if (item.Name == "catchHandler")
{
Add(result, Convert.ToInt32(item.GetAttribute("offset"), 16), "$");
}
}
}
}
else
{
foreach (XmlNode entry in doc.GetElementsByTagName("asyncInfo"))
{
foreach (XmlElement item in entry.ChildNodes)
{
if (item.Name == "await")
{
AddTextual(result, Convert.ToInt32(item.GetAttribute("yield"), 16), "async: yield");
AddTextual(result, Convert.ToInt32(item.GetAttribute("resume"), 16), "async: resume");
}
else if (item.Name == "catchHandler")
{
AddTextual(result, Convert.ToInt32(item.GetAttribute("offset"), 16), "async: catch handler");
}
}
}
foreach (XmlNode entry in doc.GetElementsByTagName("sequencePoints"))
{
foreach (XmlElement item in entry.ChildNodes)
{
AddTextual(result, Convert.ToInt32(item.GetAttribute("offset"), 16), "sequence point: " + SnippetFromSpan(lines, item));
}
}
}
return result;
void Add(Dictionary<int, string> dict, int key, string value)
{
if (dict.TryGetValue(key, out string found))
{
dict[key] = found + value;
}
else
{
dict[key] = value;
}
}
void AddTextual(Dictionary<int, string> dict, int key, string value)
{
if (dict.TryGetValue(key, out string found))
{
dict[key] = found + ", " + value;
}
else
{
dict[key] = "// " + value;
}
}
}
private static string SnippetFromSpan(string[] lines, XmlElement span)
{
if (span.GetAttribute("hidden") != "true")
{
var startLine = Convert.ToInt32(span.GetAttribute("startLine"));
var startColumn = Convert.ToInt32(span.GetAttribute("startColumn"));
var endLine = Convert.ToInt32(span.GetAttribute("endLine"));
var endColumn = Convert.ToInt32(span.GetAttribute("endColumn"));
if (startLine == endLine)
{
return lines[startLine - 1].Substring(startColumn - 1, endColumn - startColumn);
}
else
{
var start = lines[startLine - 1].Substring(startColumn - 1);
var end = lines[endLine - 1].Substring(0, endColumn - 1);
return TruncateStart(start, 12) + " ... " + TruncateEnd(end, 12);
}
}
else
{
return "<hidden>";
}
string TruncateStart(string text, int maxLength)
{
if (text.Length < maxLength) { return text; }
return text.Substring(0, maxLength);
}
string TruncateEnd(string text, int maxLength)
{
if (text.Length < maxLength) { return text; }
return text.Substring(text.Length - maxLength - 1, maxLength);
}
}
}
}
......@@ -2,10 +2,15 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis;
using Microsoft.Metadata.Tools;
using Roslyn.Utilities;
using Xunit;
namespace Roslyn.Test.Utilities
......@@ -144,5 +149,38 @@ internal static IEnumerable<string> GetExportedTypesFullNames(MetadataReader met
yield return (ns.Length == 0) ? name : (ns + "." + name);
}
}
public static void VerifyMetadataEqualModuloMvid(Stream peStream1, Stream peStream2)
{
peStream1.Position = 0;
peStream2.Position = 0;
var peReader1 = new PEReader(peStream1);
var peReader2 = new PEReader(peStream2);
var md1 = peReader1.GetMetadata().GetContent();
var md2 = peReader2.GetMetadata().GetContent();
var mdReader1 = peReader1.GetMetadataReader();
var mdReader2 = peReader2.GetMetadataReader();
var mvidIndex1 = mdReader1.GetModuleDefinition().Mvid;
var mvidIndex2 = mdReader2.GetModuleDefinition().Mvid;
var mvidOffset1 = mdReader1.GetHeapMetadataOffset(HeapIndex.Guid) + 16 * (MetadataTokens.GetHeapOffset(mvidIndex1) - 1);
var mvidOffset2 = mdReader2.GetHeapMetadataOffset(HeapIndex.Guid) + 16 * (MetadataTokens.GetHeapOffset(mvidIndex2) - 1);
if (!md1.RemoveRange(mvidOffset1, 16).SequenceEqual(md1.RemoveRange(mvidOffset2, 16)))
{
var mdw1 = new StringWriter();
var mdw2 = new StringWriter();
new MetadataVisualizer(mdReader1, mdw1).Visualize();
new MetadataVisualizer(mdReader2, mdw2).Visualize();
mdw1.Flush();
mdw2.Flush();
AssertEx.AssertResultsEqual(mdw1.ToString(), mdw2.ToString());
}
}
}
}
......@@ -22,10 +22,6 @@
<Project>{7fe6b002-89d8-4298-9b1b-0b5c247dd1fd}</Project>
<Name>CompilerTestResources</Name>
</ProjectReference>
<ProjectReference Include="..\..\PdbUtilities\PdbUtilities.csproj">
<Project>{afde6bea-5038-4a4a-a88e-dbd2e4088eed}</Project>
<Name>PdbUtilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}</Project>
<Name>CodeAnalysis</Name>
......@@ -47,7 +43,6 @@
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.CommandLine.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Emit.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.WinRT.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.EnC.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.PerformanceTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Semantic.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.Symbol.UnitTests" />
......@@ -99,7 +94,7 @@
<Compile Include="Assert\EqualityUtil`1.cs" />
<Compile Include="Assert\TestExceptionUtilities.cs" />
<Compile Include="Assert\WorkItemAttribute.cs" />
<Compile Include="CommonTestBase.CompilationVerifier.cs" />
<Compile Include="CompilationVerifier.cs" />
<Compile Include="CommonTestBase.cs" />
<Compile Include="Compilation\CompilationDifference.cs" />
<Compile Include="Compilation\CompilationExtensions.cs" />
......@@ -138,7 +133,7 @@
<Compile Include="FX\EncodingUtilities.cs" />
<Compile Include="FX\EnsureEnglishUICulture.cs" />
<Compile Include="FX\EnsureInvariantCulture.cs" />
<Compile Include="FX\EventWaiter.cs" />
<Compile Include="FX\EventWaiter.cs" />
<Compile Include="FX\HResult.cs" />
<Compile Include="FX\ImmutableArrayTestExtensions.cs" />
<Compile Include="FX\MonoHelpers.cs" />
......@@ -151,12 +146,14 @@
<Compile Include="ICompilationVerifier.cs" />
<Compile Include="MarkedSource\MarkupTestFile.cs" />
<Compile Include="MarkedSource\SourceWithMarkedNodes.cs" />
<Compile Include="MetadataSignatureUnitTestHelper.cs" />
<Compile Include="Metadata\AggregatedMetadataReader.cs" />
<Compile Include="Metadata\MetadataSignatureUnitTestHelper.cs" />
<Compile Include="Metadata\CustomAttributeRow.cs" />
<Compile Include="Metadata\DynamicAnalysisDataReader.cs" />
<Compile Include="Metadata\EncValidation.cs" />
<Compile Include="Metadata\IlasmUtilities.cs" />
<Compile Include="Metadata\ILBuilderVisualizer.cs" />
<Compile Include="Metadata\ILValidation.cs" />
<Compile Include="Metadata\MetadataReaderUtils.cs" />
<Compile Include="Metadata\MetadataValidation.cs" />
<Compile Include="Metadata\ModuleData.cs" />
......@@ -173,9 +170,6 @@
<Compile Include="Mocks\TestStream.cs" />
<Compile Include="Mocks\VirtualizedRelativePathResolver.cs" />
<Compile Include="ObjectReference.cs" />
<Compile Include="Pdb\MockSymWriter.cs" />
<Compile Include="Pdb\PdbTestUtilities.cs" />
<Compile Include="Pdb\PdbValidation.cs" />
<Compile Include="Pe\BrokenStream.cs" />
<Compile Include="ReflectionAssert.cs" />
<Compile Include="Syntax\ISyntaxNodeKindProvider.cs" />
......
......@@ -62,7 +62,10 @@ public bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string targetFramewo
// project files are in the same folder--they both use the full path to the _folder_ as the canonical
// name. To distinguish them we also examine the "regular" name, which will necessarily be different
// if the two projects are in the same folder.
if (p.Hierarchy.TryGetCanonicalName((uint)VSConstants.VSITEMID.Root, out string projectCanonicalName)
// Note that if a project has been loaded with Lightweight Solution Load it won't even have a
// hierarchy, so we need to check for null first.
if (p.Hierarchy != null
&& p.Hierarchy.TryGetCanonicalName((uint)VSConstants.VSITEMID.Root, out string projectCanonicalName)
&& p.Hierarchy.TryGetItemName((uint)VSConstants.VSITEMID.Root, out string projectName)
&& projectCanonicalName.Equals(nestedCanonicalName, System.StringComparison.OrdinalIgnoreCase)
&& projectName.Equals(nestedName))
......
......@@ -143,10 +143,6 @@
<Project>{eba4dfa1-6ded-418f-a485-a3b608978906}</Project>
<Name>InteractiveHost</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\Test\PdbUtilities\PdbUtilities.csproj">
<Project>{afde6bea-5038-4a4a-a88e-dbd2e4088eed}</Project>
<Name>PdbUtilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\Scripting\Core\Scripting.csproj">
<Project>{12a68549-4e8c-42d6-8703-a09335f97997}</Project>
<Name>Scripting</Name>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册