提交 e8c3712e 编写于 作者: J Jared Parsons

Linked more files

上级 f8296d16
......@@ -60,6 +60,27 @@
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\CSharp\CompilingTestBase.cs">
<Link>CompilingTestBase.cs</Link>
</Compile>
<Compile Include="..\CSharp\CSharpTrackingDiagnosticAnalyzer.cs">
<Link>CSharpTrackingDiagnosticAnalyzer.cs</Link>
</Compile>
<Compile Include="..\CSharp\DiagnosticTestUtilities.cs">
<Link>DiagnosticTestUtilities.cs</Link>
</Compile>
<Compile Include="..\CSharp\ScriptTestFixtures.cs">
<Link>ScriptTestFixtures.cs</Link>
</Compile>
<Compile Include="..\CSharp\SemanticModelTestBase.cs">
<Link>SemanticModelTestBase.cs</Link>
</Compile>
<Compile Include="..\CSharp\SymbolUtilities.cs">
<Link>SymbolUtilities.cs</Link>
</Compile>
<Compile Include="..\CSharp\SyntaxTreeExtensions.cs">
<Link>SyntaxTreeExtensions.cs</Link>
</Compile>
<Compile Include="..\CSharp\TestOptions.cs">
<Link>TestOptions.cs</Link>
</Compile>
......@@ -69,25 +90,18 @@
<Compile Include="..\CSharp\CompilationTestUtils.cs">
<Link>CompilationTestUtils.cs</Link>
</Compile>
<Compile Include="CompilingTestBase.cs" />
<Compile Include="CSharpTestBase.cs" />
<Compile Include="CSharpTrackingDiagnosticAnalyzer.cs" />
<Compile Include="..\CSharp\DiagnosticExtensions.cs">
<Link>DiagnosticExtensions.cs</Link>
</Compile>
<Compile Include="DiagnosticTestUtilities.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="..\CSharp\LocalVariableDeclaratorsCollector.cs">
<Link>LocalVariableDeclaratorsCollector.cs</Link>
</Compile>
<Compile Include="MetadataTestHelpers.cs">
<Compile Include="..\CSharp\MetadataTestHelpers.cs">
<Link>MetadataTestHelpers.cs</Link>
</Compile>
<Compile Include="MockCSharpCompiler.cs" />
<Compile Include="ScriptTestFixtures.cs" />
<Compile Include="SemanticModelTestBase.cs" />
<Compile Include="SymbolUtilities.cs" />
<Compile Include="SyntaxTreeExtensions.cs" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleToTest Include="Roslyn.Compilers.CSharp.CommandLine.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.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities
{
public class CSharpTrackingDiagnosticAnalyzer : TrackingDiagnosticAnalyzer<SyntaxKind>
{
private static readonly Regex s_omittedSyntaxKindRegex =
new Regex(@"Using|Extern|Parameter|Constraint|Specifier|Initializer|Global|Method|Destructor|MemberBindingExpression|ElementBindingExpression|ArrowExpressionClause|NameOfExpression");
protected override bool IsOnCodeBlockSupported(SymbolKind symbolKind, MethodKind methodKind, bool returnsVoid)
{
return base.IsOnCodeBlockSupported(symbolKind, methodKind, returnsVoid) && methodKind != MethodKind.EventRaise;
}
protected override bool IsAnalyzeNodeSupported(SyntaxKind syntaxKind)
{
return base.IsAnalyzeNodeSupported(syntaxKind) && !s_omittedSyntaxKindRegex.IsMatch(syntaxKind.ToString());
}
}
}
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// OBSOLETE: Use DiagnosticDescription instead.
/// </summary>
public struct ErrorDescription
{
public bool IsWarning;
public int Code, Line, Column;
public string[] Parameters;
public override string ToString()
{
return string.Format("Line={0}, Column={1}, Code={2}, IsWarning={3}", this.Line, this.Column, this.Code, this.IsWarning);
}
}
public abstract class DiagnosticsUtils
{
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
public static void VerifyErrorCodes(CSharpCompilation comp, params ErrorDescription[] expectedErrors)
{
var actualErrors = comp.GetDiagnostics();
DiagnosticsUtils.VerifyErrorCodes(actualErrors, expectedErrors);
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
[Obsolete("Use VerifyDiagnostics", true)]
public static void TestDiagnostics(string source, params string[] diagStrings)
{
var comp = CSharpTestBase.CreateCompilationWithMscorlib(source);
var diagnostics = comp.GetDiagnostics();
CompilingTestBase.TestDiagnostics(diagnostics, diagStrings);
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
[Obsolete("Use VerifyDiagnostics", true)]
public static void TestDiagnosticsExact(string source, params string[] diagStrings)
{
var comp = CSharpTestBase.CreateCompilationWithMscorlib(source);
var diagnostics = comp.GetDiagnostics();
Assert.Equal(diagStrings.Length, diagnostics.Length);
CompilingTestBase.TestDiagnostics(diagnostics, diagStrings);
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
internal protected static CSharpCompilation VerifyErrorsAndGetCompilationWithMscorlib(string text, params ErrorDescription[] expectedErrorDesp)
{
return VerifyErrorsAndGetCompilationWithMscorlib(new string[] { text }, expectedErrorDesp);
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
internal protected static CSharpCompilation VerifyErrorsAndGetCompilationWithMscorlib(string[] srcs, params ErrorDescription[] expectedErrorDesp)
{
var comp = CSharpTestBase.CreateCompilationWithMscorlib(srcs);
var actualErrors = comp.GetDiagnostics();
VerifyErrorCodes(actualErrors, expectedErrorDesp);
return comp;
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
internal protected static CSharpCompilation VerifyErrorsAndGetCompilationWithMscorlib(string text, IEnumerable<MetadataReference> refs, params ErrorDescription[] expectedErrorDesp)
{
return VerifyErrorsAndGetCompilationWithMscorlib(new List<string> { text }, refs, expectedErrorDesp);
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
internal protected static CSharpCompilation VerifyErrorsAndGetCompilationWithMscorlib(List<string> srcs, IEnumerable<MetadataReference> refs, params ErrorDescription[] expectedErrorDesp)
{
var synTrees = (from text in srcs
select SyntaxFactory.ParseSyntaxTree(text)).ToArray();
return VerifyErrorsAndGetCompilationWithMscorlib(synTrees, refs, expectedErrorDesp);
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
internal protected static CSharpCompilation VerifyErrorsAndGetCompilationWithMscorlib(SyntaxTree[] trees, IEnumerable<MetadataReference> refs, params ErrorDescription[] expectedErrorDesp)
{
return VerifyErrorsAndGetCompilation(trees, refs.Concat(CSharpTestBase.MscorlibRef), expectedErrorDesp);
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
internal protected static CSharpCompilation VerifyErrorsAndGetCompilation(IEnumerable<SyntaxTree> synTrees, IEnumerable<MetadataReference> refs = null, params ErrorDescription[] expectedErrorDesp)
{
var comp = CSharpCompilation.Create(assemblyName: "DiagnosticsTest", options: TestOptions.ReleaseDll, syntaxTrees: synTrees, references: refs);
var actualErrors = comp.GetDiagnostics();
VerifyErrorCodes(actualErrors, expectedErrorDesp);
return comp;
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
public static void VerifyErrorCodes(IEnumerable<Diagnostic> actualErrors, params ErrorDescription[] expectedErrorDesp)
{
if (expectedErrorDesp == null)
return;
int expectedLength = expectedErrorDesp.Length;
int actualLength = actualErrors.Count();
Assert.True(
expectedLength == actualLength,
String.Format(
"ErrCount {0} != {1}{2}Actual errors are:{2}{3}",
expectedLength,
actualLength,
Environment.NewLine,
actualLength == 0 ? "<none>" : string.Join(Environment.NewLine, actualErrors)));
var actualSortedDesp = (from ae in
(from e in actualErrors
let lineSpan = e.Location.GetMappedLineSpan()
select new ErrorDescription
{
Code = e.Code,
Line = lineSpan.IsValid ? lineSpan.StartLinePosition.Line + 1 : 0,
Column = lineSpan.IsValid ? lineSpan.StartLinePosition.Character + 1 : 0,
IsWarning = e.Severity == DiagnosticSeverity.Warning,
Parameters = (e.Arguments != null && e.Arguments.Count > 0 && e.Arguments[0] != null) ?
e.Arguments.Select(x => x != null ? x.ToString() : null).ToArray() : SpecializedCollections.EmptyArray<string>()
})
orderby ae.Code, ae.Line, ae.Column
select ae).ToList();
var expectedSortedDesp = (from ee in expectedErrorDesp
orderby ee.Code, ee.Line, ee.Column
select ee).ToList();
int idx = 0;
// actual >= expected
foreach (var experr in expectedSortedDesp)
{
while (idx < actualSortedDesp.Count && actualSortedDesp[idx].Code < experr.Code)
{
idx++;
}
if (idx >= actualSortedDesp.Count)
{
idx = actualSortedDesp.Count - 1;
}
var acterr = actualSortedDesp[idx];
Assert.Equal(experr.Code, acterr.Code);
if (experr.Line > 0 && experr.Column > 0)
{
Assert.True(experr.Line == acterr.Line, String.Format("Line {0}!={1}", experr.Line, acterr.Line));
Assert.True(experr.Column == acterr.Column, String.Format("Col {0}!={1}", experr.Column, acterr.Column));
}
Assert.Equal(experr.IsWarning, acterr.IsWarning);
//if the expected contains parameters, validate those too.
if (experr.Parameters != null)
{
Assert.True(experr.Parameters.SequenceEqual(acterr.Parameters), String.Format("Param: {0}!={1}", experr.Parameters.Count(), acterr.Parameters.Count()));
}
idx++;
}
}
/// <summary>
/// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
/// </summary>
public static void VerifyErrorCodesNoLineColumn(IEnumerable<Diagnostic> actualErrors, params ErrorDescription[] expectedErrorDesp)
{
if (expectedErrorDesp == null)
return;
// TODO: for now, we only expected actual errors including all expected errors
// Assert.Equal(expectedErrorDesp.Length, actualErrors.Count);
// allow actual errors contain more same errors, no line & column check
Assert.InRange(expectedErrorDesp.Length, 0, actualErrors.Count());
var expectedCodes = (from e in expectedErrorDesp
orderby e.Code
group e by e.Code).ToList();
var actualCodes = (from e in actualErrors
orderby e.Code
group e by e.Code).ToList();
foreach (var expectedGroup in expectedCodes)
{
var actualGroup = actualCodes.SingleOrDefault(x => x.Key == expectedGroup.Key);
var actualGroupCount = actualGroup != null ? actualGroup.Count() : 0;
// Same error code *should* be same error type: error/warning
// In other words, 0 <= # of expected occurrences <= # of actual occurrences
Assert.InRange(expectedGroup.Count(), 0, actualGroupCount);
}
}
}
}
// 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.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal static class MetadataTestHelpers
{
internal static NamedTypeSymbol GetCorLibType(this ModuleSymbol module, SpecialType typeId)
{
return module.ContainingAssembly.GetSpecialType(typeId);
}
internal static AssemblySymbol CorLibrary(this ModuleSymbol module)
{
return module.ContainingAssembly.CorLibrary;
}
internal static AssemblySymbol GetSymbolForReference(MetadataReference reference)
{
return GetSymbolsForReferences(mrefs: new[] { reference })[0];
}
internal static AssemblySymbol[] GetSymbolsForReferences(params MetadataReference[] mrefs)
{
return GetSymbolsForReferences(compilations: null, bytes: null, mrefs: mrefs, options: null);
}
internal static AssemblySymbol[] GetSymbolsForReferences(MetadataReference[] mrefs, Compilation[] compilations)
{
return GetSymbolsForReferences(
mrefs: mrefs.Concat(compilations.Select(c => c.ToMetadataReference())).ToArray());
}
internal static AssemblySymbol[] GetSymbolsForReferences(
CSharpCompilation[] compilations = null,
byte[][] bytes = null,
MetadataReference[] mrefs = null,
CSharpCompilationOptions options = null)
{
var refs = new List<MetadataReference>();
if (compilations != null)
{
foreach (var c in compilations)
{
refs.Add(new CSharpCompilationReference(c));
}
}
if (bytes != null)
{
foreach (var b in bytes)
{
refs.Add(MetadataReference.CreateFromImage(b.AsImmutableOrNull()));
}
}
if (mrefs != null)
{
refs.AddRange(mrefs);
}
var tc1 = CSharpCompilation.Create(assemblyName: "Dummy", options: options ?? TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[0], references: refs);
return (from @ref in refs select tc1.GetReferencedAssemblySymbol(@ref)).ToArray();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities
{
public static class ScriptTestFixtures
{
internal static MetadataReference HostRef = MetadataReference.CreateFromAssemblyInternal(typeof(ScriptTestFixtures).GetTypeInfo().Assembly);
public class B
{
public int x = 1, w = 4;
}
public class C : B, I
{
public static readonly int StaticField = 123;
public int Y => 2;
public string N { get; set; } = "2";
public int Z() => 3;
public override int GetHashCode() => 123;
}
public interface I
{
string N { get; set; }
int Z();
}
private class PrivateClass : I
{
public string N { get; set; } = null;
public int Z() => 3;
}
public class B2
{
public int x = 1, w = 4;
}
}
}
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public abstract class SemanticModelTestBase : CSharpTestBase
{
protected List<SyntaxNode> GetSyntaxNodeList(SyntaxTree syntaxTree)
{
return GetSyntaxNodeList(syntaxTree.GetRoot(), null);
}
protected List<SyntaxNode> GetSyntaxNodeList(SyntaxNode node, List<SyntaxNode> synList)
{
if (synList == null)
synList = new List<SyntaxNode>();
synList.Add(node);
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
synList = GetSyntaxNodeList(child.AsNode(), synList);
}
return synList;
}
protected int GetPositionForBinding(SyntaxTree tree)
{
return GetSyntaxNodeForBinding(GetSyntaxNodeList(tree)).SpanStart;
}
protected int GetPositionForBinding(string code)
{
const string tag = "/*pos*/";
return code.IndexOf(tag, StringComparison.Ordinal) + tag.Length;
}
protected SyntaxNode GetSyntaxNodeForBinding(List<SyntaxNode> synList)
{
return GetSyntaxNodeOfTypeForBinding<SyntaxNode>(synList);
}
protected readonly string startString = "/*<bind>*/";
protected readonly string endString = "/*</bind>*/";
protected TNode GetSyntaxNodeOfTypeForBinding<TNode>(List<SyntaxNode> synList) where TNode : SyntaxNode
{
foreach (var node in synList.OfType<TNode>())
{
string exprFullText = node.ToFullString();
exprFullText = exprFullText.Trim();
if (exprFullText.StartsWith(startString, StringComparison.Ordinal))
{
if (exprFullText.Contains(endString))
if (exprFullText.EndsWith(endString, StringComparison.Ordinal))
return node;
else
continue;
else
return node;
}
if (exprFullText.EndsWith(endString, StringComparison.Ordinal))
{
if (exprFullText.Contains(startString))
if (exprFullText.StartsWith(startString, StringComparison.Ordinal))
return node;
else
continue;
else
return node;
}
}
return null;
}
protected List<ExpressionSyntax> GetExprSyntaxList(SyntaxTree syntaxTree)
{
return GetExprSyntaxList(syntaxTree.GetRoot(), null);
}
private List<ExpressionSyntax> GetExprSyntaxList(SyntaxNode node, List<ExpressionSyntax> exprSynList)
{
if (exprSynList == null)
exprSynList = new List<ExpressionSyntax>();
if (node is ExpressionSyntax)
{
exprSynList.Add(node as ExpressionSyntax);
}
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
exprSynList = GetExprSyntaxList(child.AsNode(), exprSynList);
}
return exprSynList;
}
protected ExpressionSyntax GetExprSyntaxForBinding(List<ExpressionSyntax> exprSynList, int index = 0)
{
var tagName = string.Format("bind{0}", index == 0 ? String.Empty : index.ToString());
var startComment = string.Format("/*<{0}>*/", tagName);
var endComment = string.Format("/*</{0}>*/", tagName);
foreach (var exprSyntax in exprSynList)
{
string exprFullText = exprSyntax.ToFullString();
exprFullText = exprFullText.Trim();
if (exprFullText.StartsWith(startComment, StringComparison.Ordinal))
{
if (exprFullText.Contains(endComment))
if (exprFullText.EndsWith(endComment, StringComparison.Ordinal))
return exprSyntax;
else
continue;
else
return exprSyntax;
}
if (exprFullText.EndsWith(endComment, StringComparison.Ordinal))
{
if (exprFullText.Contains(startComment))
if (exprFullText.StartsWith(startComment, StringComparison.Ordinal))
return exprSyntax;
else
continue;
else
return exprSyntax;
}
}
return null;
}
internal static SymbolInfo BindFirstConstructorInitializer(string source)
{
var compilation = CreateCompilationWithMscorlib(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var constructorInitializer = GetFirstConstructorInitializer(tree.GetCompilationUnitRoot());
Assert.NotNull(constructorInitializer);
return model.GetSpeculativeSymbolInfo(constructorInitializer.SpanStart, constructorInitializer);
}
private static ConstructorInitializerSyntax GetFirstConstructorInitializer(SyntaxNode node)
{
Func<SyntaxNode, bool> isConstructorInitializer = n =>
n.IsKind(SyntaxKind.BaseConstructorInitializer) || n.IsKind(SyntaxKind.ThisConstructorInitializer);
var constructorInitializers = node.DescendantNodesAndSelf(n => !(n is ExpressionSyntax)).Where(isConstructorInitializer);
return (ConstructorInitializerSyntax)constructorInitializers.FirstOrDefault();
}
protected CompilationUtils.SemanticInfoSummary GetSemanticInfoForTest<TNode>(string testSrc, CSharpParseOptions parseOptions = null) where TNode : SyntaxNode
{
var compilation = CreateCompilationWithMscorlib(testSrc, new[] { SystemCoreRef }, parseOptions: parseOptions);
return GetSemanticInfoForTest<TNode>(compilation);
}
internal CompilationUtils.SemanticInfoSummary GetSemanticInfoForTestExperimental<TNode>(string testSrc, MessageID feature) where TNode : SyntaxNode
{
var compilation = CreateExperimentalCompilationWithMscorlib45(testSrc, feature, new[] { SystemCoreRef });
return GetSemanticInfoForTest<TNode>(compilation);
}
protected CompilationUtils.SemanticInfoSummary GetSemanticInfoForTest<TNode>(CSharpCompilation compilation) where TNode : SyntaxNode
{
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var syntaxToBind = GetSyntaxNodeOfTypeForBinding<TNode>(GetSyntaxNodeList(tree));
return model.GetSemanticInfoSummary(syntaxToBind);
}
internal PreprocessingSymbolInfo GetPreprocessingSymbolInfoForTest(string testSrc, string subStrForPreprocessNameIndex)
{
var compilation = CreateCompilationWithMscorlib(testSrc, new[] { SystemCoreRef });
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var position = testSrc.IndexOf(subStrForPreprocessNameIndex, StringComparison.Ordinal);
var nameSyntaxToBind = tree.GetRoot().FindToken(position, findInsideTrivia: true).Parent as IdentifierNameSyntax;
return model.GetPreprocessingSymbolInfo(nameSyntaxToBind);
}
internal AliasSymbol GetAliasInfoForTest(string testSrc)
{
var compilation = CreateCompilationWithMscorlib(testSrc, new[] { SystemCoreRef });
return GetAliasInfoForTest(compilation);
}
internal AliasSymbol GetAliasInfoForTest(CSharpCompilation compilation)
{
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
IdentifierNameSyntax syntaxToBind = GetSyntaxNodeOfTypeForBinding<IdentifierNameSyntax>(GetSyntaxNodeList(tree));
return (AliasSymbol)model.GetAliasInfo(syntaxToBind);
}
protected CompilationUtils.SemanticInfoSummary GetSemanticInfoForTest(string testSrc)
{
return GetSemanticInfoForTest<ExpressionSyntax>(testSrc);
}
}
}
// 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class NameAndArityComparer
: IComparer<NamedTypeSymbol>
{
public int Compare(NamedTypeSymbol x, NamedTypeSymbol y) // Implements IComparer<NamedTypeSymbol).Compare
{
int result = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
if (result != 0)
{
return result;
}
return x.Arity - y.Arity;
}
}
internal static class SymbolUtilities
{
public static NamespaceSymbol ChildNamespace(this NamespaceSymbol ns, string name)
{
return ns.GetMembers()
.Where(n => n.Name.Equals(name))
.Cast<NamespaceSymbol>()
.Single();
}
public static NamedTypeSymbol ChildType(this NamespaceSymbol ns, string name)
{
return ns.GetMembers()
.OfType<NamedTypeSymbol>()
.Single(n => n.Name.Equals(name));
}
public static NamedTypeSymbol ChildType(this NamespaceSymbol ns, string name, int arity)
{
return ns.GetMembers()
.OfType<NamedTypeSymbol>()
.Single(n => n.Name.Equals(name) && n.Arity == arity);
}
public static Symbol ChildSymbol(this NamespaceOrTypeSymbol parent, string name)
{
return parent.GetMembers(name).First();
}
public static T GetIndexer<T>(this NamespaceOrTypeSymbol type, string name) where T : PropertySymbol
{
T member = type.GetMembers(WellKnownMemberNames.Indexer).Where(i => i.MetadataName == name).Single() as T;
Assert.NotNull(member);
return member;
}
public static string ListToSortedString(this List<string> list)
{
string text = "";
list.Sort();
foreach (var element in list)
{
text = text + '\n' + element.ToString();
}
return text;
}
public static string ListToSortedString<TSymbol>(this List<TSymbol> listOfSymbols) where TSymbol : ISymbol
{
string text = "";
List<string> listOfSymbolString = listOfSymbols.Select(e => e.ToTestDisplayString()).ToList();
listOfSymbolString.Sort();
foreach (var symbolString in listOfSymbolString)
{
text = text + '\n' + symbolString;
}
return text;
}
// TODO: Remove this method and fix callsites to directly invoke Microsoft.CodeAnalysis.Test.Extensions.SymbolExtensions.ToTestDisplayString().
// https://github.com/dotnet/roslyn/issues/11915
public static string ToTestDisplayString(this ISymbol symbol)
{
return CodeAnalysis.Test.Extensions.SymbolExtensions.ToTestDisplayString(symbol);
}
}
}
// 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public static class SyntaxTreeExtensions
{
public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int offset, int length, string newText)
{
var oldFullText = syntaxTree.GetText();
var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText));
return syntaxTree.WithChangedText(newFullText);
}
internal static SyntaxTree WithReplaceFirst(this SyntaxTree syntaxTree, string oldText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal);
int length = oldText.Length;
return WithReplace(syntaxTree, offset, length, newText);
}
public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int startIndex, string oldText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(oldText, startIndex, StringComparison.Ordinal); // Use an offset to find the first element to replace at
int length = oldText.Length;
return WithReplace(syntaxTree, offset, length, newText);
}
public static SyntaxTree WithInsertAt(this SyntaxTree syntaxTree, int offset, string newText)
{
return WithReplace(syntaxTree, offset, 0, newText);
}
public static SyntaxTree WithInsertBefore(this SyntaxTree syntaxTree, string existingText, string newText)
{
var oldFullText = syntaxTree.GetText().ToString();
int offset = oldFullText.IndexOf(existingText, StringComparison.Ordinal);
return WithReplace(syntaxTree, offset, 0, newText);
}
public static SyntaxTree WithRemoveAt(this SyntaxTree syntaxTree, int offset, int length)
{
return WithReplace(syntaxTree, offset, length, string.Empty);
}
public static SyntaxTree WithRemoveFirst(this SyntaxTree syntaxTree, string oldText)
{
return WithReplaceFirst(syntaxTree, oldText, string.Empty);
}
}
}
......@@ -169,9 +169,9 @@ private static ConstructorInitializerSyntax GetFirstConstructorInitializer(Synta
return (ConstructorInitializerSyntax)constructorInitializers.FirstOrDefault();
}
protected CompilationUtils.SemanticInfoSummary GetSemanticInfoForTest<TNode>(string testSrc) where TNode : SyntaxNode
protected CompilationUtils.SemanticInfoSummary GetSemanticInfoForTest<TNode>(string testSrc, CSharpParseOptions parseOptions = null) where TNode : SyntaxNode
{
var compilation = CreateCompilationWithMscorlib(testSrc, new[] { SystemCoreRef });
var compilation = CreateCompilationWithMscorlib(testSrc, new[] { SystemCoreRef }, parseOptions: parseOptions);
return GetSemanticInfoForTest<TNode>(compilation);
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册