repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
internal abstract partial class AbstractMethodXmlBuilder
{
private const string ArgumentElementName = "Argument";
private const string ArrayElementName = "Array";
private const string ArrayElementAccessElementName = "ArrayElementAccess";
private const string ArrayTypeElementName = "ArrayType";
private const string AssignmentElementName = "Assignment";
private const string BaseReferenceElementName = "BaseReference";
private const string BinaryOperationElementName = "BinaryOperation";
private const string BlockElementName = "Block";
private const string BooleanElementName = "Boolean";
private const string BoundElementName = "Bound";
private const string CastElementName = "Cast";
private const string CharElementName = "Char";
private const string CommentElementName = "Comment";
private const string ExpressionElementName = "Expression";
private const string ExpressionStatementElementName = "ExpressionStatement";
private const string LiteralElementName = "Literal";
private const string LocalElementName = "Local";
private const string MethodCallElementName = "MethodCall";
private const string NameElementName = "Name";
private const string NameRefElementName = "NameRef";
private const string NewArrayElementName = "NewArray";
private const string NewClassElementName = "NewClass";
private const string NewDelegateElementName = "NewDelegate";
private const string NullElementName = "Null";
private const string NumberElementName = "Number";
private const string ParenthesesElementName = "Parentheses";
private const string QuoteElementName = "Quote";
private const string StringElementName = "String";
private const string ThisReferenceElementName = "ThisReference";
private const string TypeElementName = "Type";
private const string BinaryOperatorAttributeName = "binaryoperator";
private const string DirectCastAttributeName = "directcast";
private const string FullNameAttributeName = "fullname";
private const string ImplicitAttributeName = "implicit";
private const string LineAttributeName = "line";
private const string NameAttributeName = "name";
private const string RankAttributeName = "rank";
private const string TryCastAttributeName = "trycast";
private const string TypeAttributeName = "type";
private const string VariableKindAttributeName = "variablekind";
private static readonly char[] s_encodedChars = new[] { '<', '>', '&' };
private static readonly string[] s_encodings = new[] { "<", ">", "&" };
private readonly StringBuilder _builder;
protected readonly IMethodSymbol Symbol;
protected readonly SemanticModel SemanticModel;
protected readonly SourceText Text;
protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel)
{
_builder = new StringBuilder();
this.Symbol = symbol;
this.SemanticModel = semanticModel;
this.Text = semanticModel.SyntaxTree.GetText();
}
public override string ToString()
=> _builder.ToString();
private void AppendEncoded(string text)
{
var length = text.Length;
var startIndex = 0;
int index;
for (index = 0; index < length; index++)
{
var encodingIndex = Array.IndexOf(s_encodedChars, text[index]);
if (encodingIndex >= 0)
{
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
_builder.Append(s_encodings[encodingIndex]);
startIndex = index + 1;
}
}
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
}
private void AppendOpenTag(string name, AttributeInfo[] attributes)
{
_builder.Append('<');
_builder.Append(name);
foreach (var attribute in attributes.Where(a => !a.IsEmpty))
{
_builder.Append(' ');
_builder.Append(attribute.Name);
_builder.Append("=\"");
AppendEncoded(attribute.Value);
_builder.Append('"');
}
_builder.Append('>');
}
private void AppendCloseTag(string name)
{
_builder.Append("</");
_builder.Append(name);
_builder.Append('>');
}
private void AppendLeafTag(string name)
{
_builder.Append('<');
_builder.Append(name);
_builder.Append("/>");
}
private static string GetBinaryOperatorKindText(BinaryOperatorKind kind)
=> kind switch
{
BinaryOperatorKind.Plus => "plus",
BinaryOperatorKind.BitwiseOr => "bitor",
BinaryOperatorKind.BitwiseAnd => "bitand",
BinaryOperatorKind.Concatenate => "concatenate",
BinaryOperatorKind.AddDelegate => "adddelegate",
_ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()),
};
private static string GetVariableKindText(VariableKind kind)
=> kind switch
{
VariableKind.Property => "property",
VariableKind.Method => "method",
VariableKind.Field => "field",
VariableKind.Local => "local",
VariableKind.Unknown => "unknown",
_ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()),
};
private IDisposable Tag(string name, params AttributeInfo[] attributes)
=> new AutoTag(this, name, attributes);
private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind)
{
if (kind == BinaryOperatorKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind));
}
private AttributeInfo FullNameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(FullNameAttributeName, name);
}
private AttributeInfo ImplicitAttribute(bool? @implicit)
{
if (@implicit == null)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no");
}
private AttributeInfo LineNumberAttribute(int lineNumber)
=> new AttributeInfo(LineAttributeName, lineNumber.ToString());
private AttributeInfo NameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(NameAttributeName, name);
}
private AttributeInfo RankAttribute(int rank)
=> new AttributeInfo(RankAttributeName, rank.ToString());
private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null)
=> specialCastKind switch
{
SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"),
SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"),
_ => AttributeInfo.Empty,
};
private AttributeInfo TypeAttribute(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(TypeAttributeName, typeName);
}
private AttributeInfo VariableKindAttribute(VariableKind kind)
{
if (kind == VariableKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind));
}
protected IDisposable ArgumentTag()
=> Tag(ArgumentElementName);
protected IDisposable ArrayElementAccessTag()
=> Tag(ArrayElementAccessElementName);
protected IDisposable ArrayTag()
=> Tag(ArrayElementName);
protected IDisposable ArrayTypeTag(int rank)
=> Tag(ArrayTypeElementName, RankAttribute(rank));
protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None)
=> Tag(AssignmentElementName, BinaryOperatorAttribute(kind));
protected void BaseReferenceTag()
=> AppendLeafTag(BaseReferenceElementName);
protected IDisposable BinaryOperationTag(BinaryOperatorKind kind)
=> Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind));
protected IDisposable BlockTag()
=> Tag(BlockElementName);
protected IDisposable BooleanTag()
=> Tag(BooleanElementName);
protected IDisposable BoundTag()
=> Tag(BoundElementName);
protected IDisposable CastTag(SpecialCastKind? specialCastKind = null)
=> Tag(CastElementName, SpecialCastKindAttribute(specialCastKind));
protected IDisposable CharTag()
=> Tag(CharElementName);
protected IDisposable CommentTag()
=> Tag(CommentElementName);
protected IDisposable ExpressionTag()
=> Tag(ExpressionElementName);
protected IDisposable ExpressionStatementTag(int lineNumber)
=> Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber));
protected IDisposable LiteralTag()
=> Tag(LiteralElementName);
protected IDisposable LocalTag(int lineNumber)
=> Tag(LocalElementName, LineNumberAttribute(lineNumber));
protected IDisposable MethodCallTag()
=> Tag(MethodCallElementName);
protected IDisposable NameTag()
=> Tag(NameElementName);
protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null)
=> Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName));
protected IDisposable NewArrayTag()
=> Tag(NewArrayElementName);
protected IDisposable NewClassTag()
=> Tag(NewClassElementName);
protected IDisposable NewDelegateTag(string name)
=> Tag(NewDelegateElementName, NameAttribute(name));
protected void NullTag()
=> AppendLeafTag(NullElementName);
protected IDisposable NumberTag(string typeName = null)
=> Tag(NumberElementName, TypeAttribute(typeName));
protected IDisposable ParenthesesTag()
=> Tag(ParenthesesElementName);
protected IDisposable QuoteTag(int lineNumber)
=> Tag(QuoteElementName, LineNumberAttribute(lineNumber));
protected IDisposable StringTag()
=> Tag(StringElementName);
protected void ThisReferenceTag()
=> AppendLeafTag(ThisReferenceElementName);
protected IDisposable TypeTag(bool? @implicit = null)
=> Tag(TypeElementName, ImplicitAttribute(@implicit));
protected void LineBreak()
=> _builder.AppendLine();
protected void EncodedText(string text)
=> AppendEncoded(text);
protected int GetMark()
=> _builder.Length;
protected void Rewind(int mark)
=> _builder.Length = mark;
protected virtual VariableKind GetVariableKind(ISymbol symbol)
{
if (symbol == null)
{
return VariableKind.Unknown;
}
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
return VariableKind.Field;
case SymbolKind.Local:
case SymbolKind.Parameter:
return VariableKind.Local;
case SymbolKind.Method:
return VariableKind.Method;
case SymbolKind.Property:
return VariableKind.Property;
default:
throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString());
}
}
protected string GetTypeName(ITypeSymbol typeSymbol)
=> MetadataNameHelpers.GetMetadataName(typeSymbol);
protected int GetLineNumber(SyntaxNode node)
=> Text.Lines.IndexOf(node.SpanStart);
protected void GenerateUnknown(SyntaxNode node)
{
using (QuoteTag(GetLineNumber(node)))
{
EncodedText(node.ToString());
}
}
protected void GenerateName(string name)
{
using (NameTag())
{
EncodedText(name);
}
}
protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false)
{
if (type.TypeKind == TypeKind.Array)
{
var arrayType = (IArrayTypeSymbol)type;
using var tag = ArrayTypeTag(arrayType.Rank);
GenerateType(arrayType.ElementType, @implicit, assemblyQualify);
}
else
{
using (TypeTag(@implicit))
{
var typeName = assemblyQualify
? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString()
: GetTypeName(type);
EncodedText(typeName);
}
}
}
protected void GenerateType(SpecialType specialType)
=> GenerateType(SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateNullLiteral()
{
using (LiteralTag())
{
NullTag();
}
}
protected void GenerateNumber(object value, ITypeSymbol type)
{
using (NumberTag(GetTypeName(type)))
{
if (value is double d)
{
// Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit
EncodedText(d.ToString("G17", CultureInfo.InvariantCulture));
}
else if (value is float f)
{
EncodedText(f.ToString("R", CultureInfo.InvariantCulture));
}
else
{
EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture));
}
}
}
protected void GenerateNumber(object value, SpecialType specialType)
=> GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateChar(char value)
{
using (CharTag())
{
EncodedText(value.ToString());
}
}
protected void GenerateString(string value)
{
using (StringTag())
{
EncodedText(value);
}
}
protected void GenerateBoolean(bool value)
{
using (BooleanTag())
{
EncodedText(value.ToString().ToLower());
}
}
protected void GenerateThisReference()
=> ThisReferenceTag();
protected void GenerateBaseReference()
=> BaseReferenceTag();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
internal abstract partial class AbstractMethodXmlBuilder
{
private const string ArgumentElementName = "Argument";
private const string ArrayElementName = "Array";
private const string ArrayElementAccessElementName = "ArrayElementAccess";
private const string ArrayTypeElementName = "ArrayType";
private const string AssignmentElementName = "Assignment";
private const string BaseReferenceElementName = "BaseReference";
private const string BinaryOperationElementName = "BinaryOperation";
private const string BlockElementName = "Block";
private const string BooleanElementName = "Boolean";
private const string BoundElementName = "Bound";
private const string CastElementName = "Cast";
private const string CharElementName = "Char";
private const string CommentElementName = "Comment";
private const string ExpressionElementName = "Expression";
private const string ExpressionStatementElementName = "ExpressionStatement";
private const string LiteralElementName = "Literal";
private const string LocalElementName = "Local";
private const string MethodCallElementName = "MethodCall";
private const string NameElementName = "Name";
private const string NameRefElementName = "NameRef";
private const string NewArrayElementName = "NewArray";
private const string NewClassElementName = "NewClass";
private const string NewDelegateElementName = "NewDelegate";
private const string NullElementName = "Null";
private const string NumberElementName = "Number";
private const string ParenthesesElementName = "Parentheses";
private const string QuoteElementName = "Quote";
private const string StringElementName = "String";
private const string ThisReferenceElementName = "ThisReference";
private const string TypeElementName = "Type";
private const string BinaryOperatorAttributeName = "binaryoperator";
private const string DirectCastAttributeName = "directcast";
private const string FullNameAttributeName = "fullname";
private const string ImplicitAttributeName = "implicit";
private const string LineAttributeName = "line";
private const string NameAttributeName = "name";
private const string RankAttributeName = "rank";
private const string TryCastAttributeName = "trycast";
private const string TypeAttributeName = "type";
private const string VariableKindAttributeName = "variablekind";
private static readonly char[] s_encodedChars = new[] { '<', '>', '&' };
private static readonly string[] s_encodings = new[] { "<", ">", "&" };
private readonly StringBuilder _builder;
protected readonly IMethodSymbol Symbol;
protected readonly SemanticModel SemanticModel;
protected readonly SourceText Text;
protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel)
{
_builder = new StringBuilder();
this.Symbol = symbol;
this.SemanticModel = semanticModel;
this.Text = semanticModel.SyntaxTree.GetText();
}
public override string ToString()
=> _builder.ToString();
private void AppendEncoded(string text)
{
var length = text.Length;
var startIndex = 0;
int index;
for (index = 0; index < length; index++)
{
var encodingIndex = Array.IndexOf(s_encodedChars, text[index]);
if (encodingIndex >= 0)
{
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
_builder.Append(s_encodings[encodingIndex]);
startIndex = index + 1;
}
}
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
}
private void AppendOpenTag(string name, AttributeInfo[] attributes)
{
_builder.Append('<');
_builder.Append(name);
foreach (var attribute in attributes.Where(a => !a.IsEmpty))
{
_builder.Append(' ');
_builder.Append(attribute.Name);
_builder.Append("=\"");
AppendEncoded(attribute.Value);
_builder.Append('"');
}
_builder.Append('>');
}
private void AppendCloseTag(string name)
{
_builder.Append("</");
_builder.Append(name);
_builder.Append('>');
}
private void AppendLeafTag(string name)
{
_builder.Append('<');
_builder.Append(name);
_builder.Append("/>");
}
private static string GetBinaryOperatorKindText(BinaryOperatorKind kind)
=> kind switch
{
BinaryOperatorKind.Plus => "plus",
BinaryOperatorKind.BitwiseOr => "bitor",
BinaryOperatorKind.BitwiseAnd => "bitand",
BinaryOperatorKind.Concatenate => "concatenate",
BinaryOperatorKind.AddDelegate => "adddelegate",
_ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()),
};
private static string GetVariableKindText(VariableKind kind)
=> kind switch
{
VariableKind.Property => "property",
VariableKind.Method => "method",
VariableKind.Field => "field",
VariableKind.Local => "local",
VariableKind.Unknown => "unknown",
_ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()),
};
private IDisposable Tag(string name, params AttributeInfo[] attributes)
=> new AutoTag(this, name, attributes);
private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind)
{
if (kind == BinaryOperatorKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind));
}
private AttributeInfo FullNameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(FullNameAttributeName, name);
}
private AttributeInfo ImplicitAttribute(bool? @implicit)
{
if (@implicit == null)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no");
}
private AttributeInfo LineNumberAttribute(int lineNumber)
=> new AttributeInfo(LineAttributeName, lineNumber.ToString());
private AttributeInfo NameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(NameAttributeName, name);
}
private AttributeInfo RankAttribute(int rank)
=> new AttributeInfo(RankAttributeName, rank.ToString());
private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null)
=> specialCastKind switch
{
SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"),
SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"),
_ => AttributeInfo.Empty,
};
private AttributeInfo TypeAttribute(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(TypeAttributeName, typeName);
}
private AttributeInfo VariableKindAttribute(VariableKind kind)
{
if (kind == VariableKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind));
}
protected IDisposable ArgumentTag()
=> Tag(ArgumentElementName);
protected IDisposable ArrayElementAccessTag()
=> Tag(ArrayElementAccessElementName);
protected IDisposable ArrayTag()
=> Tag(ArrayElementName);
protected IDisposable ArrayTypeTag(int rank)
=> Tag(ArrayTypeElementName, RankAttribute(rank));
protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None)
=> Tag(AssignmentElementName, BinaryOperatorAttribute(kind));
protected void BaseReferenceTag()
=> AppendLeafTag(BaseReferenceElementName);
protected IDisposable BinaryOperationTag(BinaryOperatorKind kind)
=> Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind));
protected IDisposable BlockTag()
=> Tag(BlockElementName);
protected IDisposable BooleanTag()
=> Tag(BooleanElementName);
protected IDisposable BoundTag()
=> Tag(BoundElementName);
protected IDisposable CastTag(SpecialCastKind? specialCastKind = null)
=> Tag(CastElementName, SpecialCastKindAttribute(specialCastKind));
protected IDisposable CharTag()
=> Tag(CharElementName);
protected IDisposable CommentTag()
=> Tag(CommentElementName);
protected IDisposable ExpressionTag()
=> Tag(ExpressionElementName);
protected IDisposable ExpressionStatementTag(int lineNumber)
=> Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber));
protected IDisposable LiteralTag()
=> Tag(LiteralElementName);
protected IDisposable LocalTag(int lineNumber)
=> Tag(LocalElementName, LineNumberAttribute(lineNumber));
protected IDisposable MethodCallTag()
=> Tag(MethodCallElementName);
protected IDisposable NameTag()
=> Tag(NameElementName);
protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null)
=> Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName));
protected IDisposable NewArrayTag()
=> Tag(NewArrayElementName);
protected IDisposable NewClassTag()
=> Tag(NewClassElementName);
protected IDisposable NewDelegateTag(string name)
=> Tag(NewDelegateElementName, NameAttribute(name));
protected void NullTag()
=> AppendLeafTag(NullElementName);
protected IDisposable NumberTag(string typeName = null)
=> Tag(NumberElementName, TypeAttribute(typeName));
protected IDisposable ParenthesesTag()
=> Tag(ParenthesesElementName);
protected IDisposable QuoteTag(int lineNumber)
=> Tag(QuoteElementName, LineNumberAttribute(lineNumber));
protected IDisposable StringTag()
=> Tag(StringElementName);
protected void ThisReferenceTag()
=> AppendLeafTag(ThisReferenceElementName);
protected IDisposable TypeTag(bool? @implicit = null)
=> Tag(TypeElementName, ImplicitAttribute(@implicit));
protected void LineBreak()
=> _builder.AppendLine();
protected void EncodedText(string text)
=> AppendEncoded(text);
protected int GetMark()
=> _builder.Length;
protected void Rewind(int mark)
=> _builder.Length = mark;
protected virtual VariableKind GetVariableKind(ISymbol symbol)
{
if (symbol == null)
{
return VariableKind.Unknown;
}
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
return VariableKind.Field;
case SymbolKind.Local:
case SymbolKind.Parameter:
return VariableKind.Local;
case SymbolKind.Method:
return VariableKind.Method;
case SymbolKind.Property:
return VariableKind.Property;
default:
throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString());
}
}
protected string GetTypeName(ITypeSymbol typeSymbol)
=> MetadataNameHelpers.GetMetadataName(typeSymbol);
protected int GetLineNumber(SyntaxNode node)
=> Text.Lines.IndexOf(node.SpanStart);
protected void GenerateUnknown(SyntaxNode node)
{
using (QuoteTag(GetLineNumber(node)))
{
EncodedText(node.ToString());
}
}
protected void GenerateName(string name)
{
using (NameTag())
{
EncodedText(name);
}
}
protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false)
{
if (type.TypeKind == TypeKind.Array)
{
var arrayType = (IArrayTypeSymbol)type;
using var tag = ArrayTypeTag(arrayType.Rank);
GenerateType(arrayType.ElementType, @implicit, assemblyQualify);
}
else
{
using (TypeTag(@implicit))
{
var typeName = assemblyQualify
? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString()
: GetTypeName(type);
EncodedText(typeName);
}
}
}
protected void GenerateType(SpecialType specialType)
=> GenerateType(SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateNullLiteral()
{
using (LiteralTag())
{
NullTag();
}
}
protected void GenerateNumber(object value, ITypeSymbol type)
{
using (NumberTag(GetTypeName(type)))
{
if (value is double d)
{
// Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit
EncodedText(d.ToString("G17", CultureInfo.InvariantCulture));
}
else if (value is float f)
{
EncodedText(f.ToString("R", CultureInfo.InvariantCulture));
}
else
{
EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture));
}
}
}
protected void GenerateNumber(object value, SpecialType specialType)
=> GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateChar(char value)
{
using (CharTag())
{
EncodedText(value.ToString());
}
}
protected void GenerateString(string value)
{
using (StringTag())
{
EncodedText(value);
}
}
protected void GenerateBoolean(bool value)
{
using (BooleanTag())
{
EncodedText(value.ToString().ToLower());
}
}
protected void GenerateThisReference()
=> ThisReferenceTag();
protected void GenerateBaseReference()
=> BaseReferenceTag();
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/EditorConfigSettings/Formatting/View/ColumnDefnitions/FormattingValueColumnDefinition.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Utilities;
using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Formatting;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.View.ColumnDefnitions
{
[Export(typeof(ITableColumnDefinition))]
[Name(Value)]
internal class FormattingValueColumnDefinition : TableColumnDefinitionBase
{
private readonly IEnumerable<IEnumSettingViewModelFactory> _factories;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FormattingValueColumnDefinition([ImportMany] IEnumerable<IEnumSettingViewModelFactory> factories)
{
_factories = factories;
}
public override string Name => Value;
public override string DisplayName => ServicesVSResources.Value;
public override double MinWidth => 80;
public override bool DefaultVisible => false;
public override bool IsFilterable => false;
public override bool IsSortable => false;
public override TextWrapping TextWrapping => TextWrapping.NoWrap;
public override bool TryCreateColumnContent(ITableEntryHandle entry, bool singleColumnView, out FrameworkElement? content)
{
if (!entry.TryGetValue(Value, out FormattingSetting setting))
{
content = null;
return false;
}
if (setting.Type == typeof(bool))
{
content = new FormattingBoolSettingView(setting);
return true;
}
foreach (var factory in _factories)
{
if (factory.IsSupported(setting.Key))
{
var viewModel = factory.CreateViewModel(setting);
content = new EnumSettingView(viewModel);
return true;
}
}
content = null;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Utilities;
using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.Formatting;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.View.ColumnDefnitions
{
[Export(typeof(ITableColumnDefinition))]
[Name(Value)]
internal class FormattingValueColumnDefinition : TableColumnDefinitionBase
{
private readonly IEnumerable<IEnumSettingViewModelFactory> _factories;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FormattingValueColumnDefinition([ImportMany] IEnumerable<IEnumSettingViewModelFactory> factories)
{
_factories = factories;
}
public override string Name => Value;
public override string DisplayName => ServicesVSResources.Value;
public override double MinWidth => 80;
public override bool DefaultVisible => false;
public override bool IsFilterable => false;
public override bool IsSortable => false;
public override TextWrapping TextWrapping => TextWrapping.NoWrap;
public override bool TryCreateColumnContent(ITableEntryHandle entry, bool singleColumnView, out FrameworkElement? content)
{
if (!entry.TryGetValue(Value, out FormattingSetting setting))
{
content = null;
return false;
}
if (setting.Type == typeof(bool))
{
content = new FormattingBoolSettingView(setting);
return true;
}
foreach (var factory in _factories)
{
if (factory.IsSupported(setting.Key))
{
var viewModel = factory.CreateViewModel(setting);
content = new EnumSettingView(viewModel);
return true;
}
}
content = null;
return false;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Diagnostic/CommonDiagnosticComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class CommonDiagnosticComparer : IEqualityComparer<Diagnostic>
{
internal static readonly CommonDiagnosticComparer Instance = new CommonDiagnosticComparer();
private CommonDiagnosticComparer()
{
}
public bool Equals(Diagnostic? x, Diagnostic? y)
{
if (object.ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
return x.Location == y.Location && x.Id == y.Id;
}
public int GetHashCode(Diagnostic obj)
{
if (object.ReferenceEquals(obj, null))
{
return 0;
}
return Hash.Combine(obj.Location, obj.Id.GetHashCode());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal sealed class CommonDiagnosticComparer : IEqualityComparer<Diagnostic>
{
internal static readonly CommonDiagnosticComparer Instance = new CommonDiagnosticComparer();
private CommonDiagnosticComparer()
{
}
public bool Equals(Diagnostic? x, Diagnostic? y)
{
if (object.ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
return x.Location == y.Location && x.Id == y.Id;
}
public int GetHashCode(Diagnostic obj)
{
if (object.ReferenceEquals(obj, null))
{
return 0;
}
return Hash.Combine(obj.Location, obj.Id.GetHashCode());
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_BuildSynchronization.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class DiagnosticAnalyzerService
{
/// <summary>
/// Synchronize build errors with live error.
/// </summary>
public ValueTask SynchronizeWithBuildAsync(
Workspace workspace,
ImmutableDictionary<ProjectId,
ImmutableArray<DiagnosticData>> diagnostics,
TaskQueue postBuildAndErrorListRefreshTaskQueue,
bool onBuildCompleted,
CancellationToken cancellationToken)
{
return _map.TryGetValue(workspace, out var analyzer)
? analyzer.SynchronizeWithBuildAsync(diagnostics, postBuildAndErrorListRefreshTaskQueue, onBuildCompleted, cancellationToken)
: default;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class DiagnosticAnalyzerService
{
/// <summary>
/// Synchronize build errors with live error.
/// </summary>
public ValueTask SynchronizeWithBuildAsync(
Workspace workspace,
ImmutableDictionary<ProjectId,
ImmutableArray<DiagnosticData>> diagnostics,
TaskQueue postBuildAndErrorListRefreshTaskQueue,
bool onBuildCompleted,
CancellationToken cancellationToken)
{
return _map.TryGetValue(workspace, out var analyzer)
? analyzer.SynchronizeWithBuildAsync(diagnostics, postBuildAndErrorListRefreshTaskQueue, onBuildCompleted, cancellationToken)
: default;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/CodeRefactorings/ExportCodeRefactoringProviderAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Use this attribute to declare a <see cref="CodeRefactoringProvider"/> implementation so that it can be discovered by the host.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExportCodeRefactoringProviderAttribute : ExportAttribute
{
/// <summary>
/// The name of the <see cref="CodeRefactoringProvider"/>.
/// </summary>
[DisallowNull]
public string? Name { get; set; }
/// <summary>
/// The source languages for which this provider can provide refactorings. See <see cref="LanguageNames"/>.
/// </summary>
public string[] Languages { get; }
/// <summary>
/// Attribute constructor used to specify availability of a code refactoring provider.
/// </summary>
/// <param name="firstLanguage">One language to which the code refactoring provider applies.</param>
/// <param name="additionalLanguages">Additional languages to which the code refactoring provider applies. See <see cref="LanguageNames"/>.</param>
public ExportCodeRefactoringProviderAttribute(string firstLanguage, params string[] additionalLanguages)
: base(typeof(CodeRefactoringProvider))
{
if (additionalLanguages == null)
{
throw new ArgumentNullException(nameof(additionalLanguages));
}
var languages = new string[additionalLanguages.Length + 1];
languages[0] = firstLanguage ?? throw new ArgumentNullException(nameof(firstLanguage));
for (var index = 0; index < additionalLanguages.Length; index++)
{
languages[index + 1] = additionalLanguages[index];
}
this.Languages = languages;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Use this attribute to declare a <see cref="CodeRefactoringProvider"/> implementation so that it can be discovered by the host.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExportCodeRefactoringProviderAttribute : ExportAttribute
{
/// <summary>
/// The name of the <see cref="CodeRefactoringProvider"/>.
/// </summary>
[DisallowNull]
public string? Name { get; set; }
/// <summary>
/// The source languages for which this provider can provide refactorings. See <see cref="LanguageNames"/>.
/// </summary>
public string[] Languages { get; }
/// <summary>
/// Attribute constructor used to specify availability of a code refactoring provider.
/// </summary>
/// <param name="firstLanguage">One language to which the code refactoring provider applies.</param>
/// <param name="additionalLanguages">Additional languages to which the code refactoring provider applies. See <see cref="LanguageNames"/>.</param>
public ExportCodeRefactoringProviderAttribute(string firstLanguage, params string[] additionalLanguages)
: base(typeof(CodeRefactoringProvider))
{
if (additionalLanguages == null)
{
throw new ArgumentNullException(nameof(additionalLanguages));
}
var languages = new string[additionalLanguages.Length + 1];
languages[0] = firstLanguage ?? throw new ArgumentNullException(nameof(firstLanguage));
for (var index = 0; index < additionalLanguages.Length; index++)
{
languages[index + 1] = additionalLanguages[index];
}
this.Languages = languages;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// We only build the Source Generator in the netstandard target
#if NETSTANDARD
#nullable enable
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace CSharpSyntaxGenerator
{
[Generator]
public sealed class SourceGenerator : CachingSourceGenerator
{
private static readonly DiagnosticDescriptor s_MissingSyntaxXml = new DiagnosticDescriptor(
"CSSG1001",
title: "Syntax.xml is missing",
messageFormat: "The Syntax.xml file was not included in the project, so we are not generating source.",
category: "SyntaxGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor s_UnableToReadSyntaxXml = new DiagnosticDescriptor(
"CSSG1002",
title: "Syntax.xml could not be read",
messageFormat: "The Syntax.xml file could not even be read. Does it exist?",
category: "SyntaxGenerator",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor s_SyntaxXmlError = new DiagnosticDescriptor(
"CSSG1003",
title: "Syntax.xml has a syntax error",
messageFormat: "{0}",
category: "SyntaxGenerator",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
protected override bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText)
{
input = context.AdditionalFiles.SingleOrDefault(a => Path.GetFileName(a.Path) == "Syntax.xml");
if (input == null)
{
context.ReportDiagnostic(Diagnostic.Create(s_MissingSyntaxXml, location: null));
inputText = null;
return false;
}
inputText = input.GetText();
if (inputText == null)
{
context.ReportDiagnostic(Diagnostic.Create(s_UnableToReadSyntaxXml, location: null));
return false;
}
return true;
}
protected override bool TryGenerateSources(
AdditionalText input,
SourceText inputText,
out ImmutableArray<(string hintName, SourceText sourceText)> sources,
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken)
{
Tree tree;
var reader = XmlReader.Create(new SourceTextReader(inputText), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit });
try
{
var serializer = new XmlSerializer(typeof(Tree));
tree = (Tree)serializer.Deserialize(reader);
}
catch (InvalidOperationException ex) when (ex.InnerException is XmlException)
{
var xmlException = (XmlException)ex.InnerException;
var line = inputText.Lines[xmlException.LineNumber - 1]; // LineNumber is one-based.
int offset = xmlException.LinePosition - 1; // LinePosition is one-based
var position = line.Start + offset;
var span = new TextSpan(position, 0);
var lineSpan = inputText.Lines.GetLinePositionSpan(span);
sources = default;
diagnostics = ImmutableArray.Create(
Diagnostic.Create(
s_SyntaxXmlError,
location: Location.Create(input.Path, span, lineSpan),
xmlException.Message));
return false;
}
TreeFlattening.FlattenChildren(tree);
var sourcesBuilder = ImmutableArray.CreateBuilder<(string hintName, SourceText sourceText)>();
addResult(writer => SourceWriter.WriteMain(writer, tree, cancellationToken), "Syntax.xml.Main.Generated.cs");
addResult(writer => SourceWriter.WriteInternal(writer, tree, cancellationToken), "Syntax.xml.Internal.Generated.cs");
addResult(writer => SourceWriter.WriteSyntax(writer, tree, cancellationToken), "Syntax.xml.Syntax.Generated.cs");
sources = sourcesBuilder.ToImmutable();
diagnostics = ImmutableArray<Diagnostic>.Empty;
return true;
void addResult(Action<TextWriter> writeFunction, string hintName)
{
// Write out the contents to a StringBuilder to avoid creating a single large string
// in memory
var stringBuilder = new StringBuilder();
using (var textWriter = new StringWriter(stringBuilder))
{
writeFunction(textWriter);
}
// And create a SourceText from the StringBuilder, once again avoiding allocating a single massive string
var sourceText = SourceText.From(new StringBuilderReader(stringBuilder), stringBuilder.Length, encoding: Encoding.UTF8);
sourcesBuilder.Add((hintName, sourceText));
}
}
private sealed class SourceTextReader : TextReader
{
private readonly SourceText _sourceText;
private int _position;
public SourceTextReader(SourceText sourceText)
{
_sourceText = sourceText;
_position = 0;
}
public override int Peek()
{
if (_position == _sourceText.Length)
{
return -1;
}
return _sourceText[_position];
}
public override int Read()
{
if (_position == _sourceText.Length)
{
return -1;
}
return _sourceText[_position++];
}
public override int Read(char[] buffer, int index, int count)
{
var charsToCopy = Math.Min(count, _sourceText.Length - _position);
_sourceText.CopyTo(_position, buffer, index, charsToCopy);
_position += charsToCopy;
return charsToCopy;
}
}
private sealed class StringBuilderReader : TextReader
{
private readonly StringBuilder _stringBuilder;
private int _position;
public StringBuilderReader(StringBuilder stringBuilder)
{
_stringBuilder = stringBuilder;
_position = 0;
}
public override int Peek()
{
if (_position == _stringBuilder.Length)
{
return -1;
}
return _stringBuilder[_position];
}
public override int Read()
{
if (_position == _stringBuilder.Length)
{
return -1;
}
return _stringBuilder[_position++];
}
public override int Read(char[] buffer, int index, int count)
{
var charsToCopy = Math.Min(count, _stringBuilder.Length - _position);
_stringBuilder.CopyTo(_position, buffer, index, charsToCopy);
_position += charsToCopy;
return charsToCopy;
}
}
}
}
#endif
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// We only build the Source Generator in the netstandard target
#if NETSTANDARD
#nullable enable
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace CSharpSyntaxGenerator
{
[Generator]
public sealed class SourceGenerator : CachingSourceGenerator
{
private static readonly DiagnosticDescriptor s_MissingSyntaxXml = new DiagnosticDescriptor(
"CSSG1001",
title: "Syntax.xml is missing",
messageFormat: "The Syntax.xml file was not included in the project, so we are not generating source.",
category: "SyntaxGenerator",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor s_UnableToReadSyntaxXml = new DiagnosticDescriptor(
"CSSG1002",
title: "Syntax.xml could not be read",
messageFormat: "The Syntax.xml file could not even be read. Does it exist?",
category: "SyntaxGenerator",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor s_SyntaxXmlError = new DiagnosticDescriptor(
"CSSG1003",
title: "Syntax.xml has a syntax error",
messageFormat: "{0}",
category: "SyntaxGenerator",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
protected override bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText)
{
input = context.AdditionalFiles.SingleOrDefault(a => Path.GetFileName(a.Path) == "Syntax.xml");
if (input == null)
{
context.ReportDiagnostic(Diagnostic.Create(s_MissingSyntaxXml, location: null));
inputText = null;
return false;
}
inputText = input.GetText();
if (inputText == null)
{
context.ReportDiagnostic(Diagnostic.Create(s_UnableToReadSyntaxXml, location: null));
return false;
}
return true;
}
protected override bool TryGenerateSources(
AdditionalText input,
SourceText inputText,
out ImmutableArray<(string hintName, SourceText sourceText)> sources,
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken)
{
Tree tree;
var reader = XmlReader.Create(new SourceTextReader(inputText), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit });
try
{
var serializer = new XmlSerializer(typeof(Tree));
tree = (Tree)serializer.Deserialize(reader);
}
catch (InvalidOperationException ex) when (ex.InnerException is XmlException)
{
var xmlException = (XmlException)ex.InnerException;
var line = inputText.Lines[xmlException.LineNumber - 1]; // LineNumber is one-based.
int offset = xmlException.LinePosition - 1; // LinePosition is one-based
var position = line.Start + offset;
var span = new TextSpan(position, 0);
var lineSpan = inputText.Lines.GetLinePositionSpan(span);
sources = default;
diagnostics = ImmutableArray.Create(
Diagnostic.Create(
s_SyntaxXmlError,
location: Location.Create(input.Path, span, lineSpan),
xmlException.Message));
return false;
}
TreeFlattening.FlattenChildren(tree);
var sourcesBuilder = ImmutableArray.CreateBuilder<(string hintName, SourceText sourceText)>();
addResult(writer => SourceWriter.WriteMain(writer, tree, cancellationToken), "Syntax.xml.Main.Generated.cs");
addResult(writer => SourceWriter.WriteInternal(writer, tree, cancellationToken), "Syntax.xml.Internal.Generated.cs");
addResult(writer => SourceWriter.WriteSyntax(writer, tree, cancellationToken), "Syntax.xml.Syntax.Generated.cs");
sources = sourcesBuilder.ToImmutable();
diagnostics = ImmutableArray<Diagnostic>.Empty;
return true;
void addResult(Action<TextWriter> writeFunction, string hintName)
{
// Write out the contents to a StringBuilder to avoid creating a single large string
// in memory
var stringBuilder = new StringBuilder();
using (var textWriter = new StringWriter(stringBuilder))
{
writeFunction(textWriter);
}
// And create a SourceText from the StringBuilder, once again avoiding allocating a single massive string
var sourceText = SourceText.From(new StringBuilderReader(stringBuilder), stringBuilder.Length, encoding: Encoding.UTF8);
sourcesBuilder.Add((hintName, sourceText));
}
}
private sealed class SourceTextReader : TextReader
{
private readonly SourceText _sourceText;
private int _position;
public SourceTextReader(SourceText sourceText)
{
_sourceText = sourceText;
_position = 0;
}
public override int Peek()
{
if (_position == _sourceText.Length)
{
return -1;
}
return _sourceText[_position];
}
public override int Read()
{
if (_position == _sourceText.Length)
{
return -1;
}
return _sourceText[_position++];
}
public override int Read(char[] buffer, int index, int count)
{
var charsToCopy = Math.Min(count, _sourceText.Length - _position);
_sourceText.CopyTo(_position, buffer, index, charsToCopy);
_position += charsToCopy;
return charsToCopy;
}
}
private sealed class StringBuilderReader : TextReader
{
private readonly StringBuilder _stringBuilder;
private int _position;
public StringBuilderReader(StringBuilder stringBuilder)
{
_stringBuilder = stringBuilder;
_position = 0;
}
public override int Peek()
{
if (_position == _stringBuilder.Length)
{
return -1;
}
return _stringBuilder[_position];
}
public override int Read()
{
if (_position == _stringBuilder.Length)
{
return -1;
}
return _stringBuilder[_position++];
}
public override int Read(char[] buffer, int index, int count)
{
var charsToCopy = Math.Min(count, _stringBuilder.Length - _position);
_stringBuilder.CopyTo(_position, buffer, index, charsToCopy);
_position += charsToCopy;
return charsToCopy;
}
}
}
}
#endif
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/OperatorPrecedence.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
/// <summary>
/// Operator precedence classes from section 7.3.1 of the C# language specification.
/// </summary>
internal enum OperatorPrecedence
{
None = 0,
AssignmentAndLambdaExpression,
Conditional,
NullCoalescing,
ConditionalOr,
ConditionalAnd,
LogicalOr,
LogicalXor,
LogicalAnd,
Equality,
RelationalAndTypeTesting,
Shift,
Additive,
Multiplicative,
Switch,
Range,
Unary,
Primary
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
/// <summary>
/// Operator precedence classes from section 7.3.1 of the C# language specification.
/// </summary>
internal enum OperatorPrecedence
{
None = 0,
AssignmentAndLambdaExpression,
Conditional,
NullCoalescing,
ConditionalOr,
ConditionalAnd,
LogicalOr,
LogicalXor,
LogicalAnd,
Equality,
RelationalAndTypeTesting,
Shift,
Additive,
Multiplicative,
Switch,
Range,
Unary,
Primary
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/CodeRefactorings/CodeRefactoring.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Represents a set of transformations that can be applied to a piece of code.
/// </summary>
internal class CodeRefactoring
{
public CodeRefactoringProvider Provider { get; }
/// <summary>
/// List of tuples of possible actions that can be used to transform the code the TextSpan within the original document they're applicable to.
/// </summary>
/// <remarks>
/// applicableToSpan should represent a logical section within the original document that the action is
/// applicable to. It doesn't have to precisely represent the exact <see cref="TextSpan"/> that will get changed.
/// </remarks>
public ImmutableArray<(CodeAction action, TextSpan? applicableToSpan)> CodeActions { get; }
public CodeRefactoring(CodeRefactoringProvider provider, ImmutableArray<(CodeAction, TextSpan?)> actions)
{
Provider = provider;
CodeActions = actions.NullToEmpty();
if (CodeActions.IsEmpty)
{
throw new ArgumentException(FeaturesResources.Actions_can_not_be_empty, nameof(actions));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Represents a set of transformations that can be applied to a piece of code.
/// </summary>
internal class CodeRefactoring
{
public CodeRefactoringProvider Provider { get; }
/// <summary>
/// List of tuples of possible actions that can be used to transform the code the TextSpan within the original document they're applicable to.
/// </summary>
/// <remarks>
/// applicableToSpan should represent a logical section within the original document that the action is
/// applicable to. It doesn't have to precisely represent the exact <see cref="TextSpan"/> that will get changed.
/// </remarks>
public ImmutableArray<(CodeAction action, TextSpan? applicableToSpan)> CodeActions { get; }
public CodeRefactoring(CodeRefactoringProvider provider, ImmutableArray<(CodeAction, TextSpan?)> actions)
{
Provider = provider;
CodeActions = actions.NullToEmpty();
if (CodeActions.IsEmpty)
{
throw new ArgumentException(FeaturesResources.Actions_can_not_be_empty, nameof(actions));
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.RemoveAnalyzerConfigDocumentUndoUnit.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class VisualStudioWorkspaceImpl
{
private class RemoveAnalyzerConfigDocumentUndoUnit : AbstractRemoveDocumentUndoUnit
{
public RemoveAnalyzerConfigDocumentUndoUnit(
VisualStudioWorkspaceImpl workspace,
DocumentId documentId)
: base(workspace, documentId)
{
}
protected override IReadOnlyList<DocumentId> GetDocumentIds(Project fromProject)
=> fromProject.State.AnalyzerConfigDocumentStates.Ids;
protected override TextDocument? GetDocument(Solution currentSolution)
=> currentSolution.GetAnalyzerConfigDocument(this.DocumentId);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class VisualStudioWorkspaceImpl
{
private class RemoveAnalyzerConfigDocumentUndoUnit : AbstractRemoveDocumentUndoUnit
{
public RemoveAnalyzerConfigDocumentUndoUnit(
VisualStudioWorkspaceImpl workspace,
DocumentId documentId)
: base(workspace, documentId)
{
}
protected override IReadOnlyList<DocumentId> GetDocumentIds(Project fromProject)
=> fromProject.State.AnalyzerConfigDocumentStates.Ids;
protected override TextDocument? GetDocument(Solution currentSolution)
=> currentSolution.GetAnalyzerConfigDocument(this.DocumentId);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeEvent.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeEvent))]
public sealed partial class CodeEvent : AbstractCodeMember, EnvDTE80.CodeEvent
{
internal static EnvDTE80.CodeEvent Create(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
{
var element = new CodeEvent(state, fileCodeModel, nodeKey, nodeKind);
var result = (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);
fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result);
return result;
}
internal static EnvDTE80.CodeEvent CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
{
var element = new CodeEvent(state, fileCodeModel, nodeKind, name);
return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);
}
private CodeEvent(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
: base(state, fileCodeModel, nodeKey, nodeKind)
{
}
private CodeEvent(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind, name)
{
}
private IEventSymbol EventSymbol
{
get { return (IEventSymbol)LookupSymbol(); }
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementEvent; }
}
public override EnvDTE.CodeElements Children
{
get { return this.Attributes; }
}
public EnvDTE.CodeFunction Adder
{
get
{
if (IsPropertyStyleEvent)
{
return CodeAccessorFunction.Create(this.State, this, MethodKind.EventAdd);
}
return null;
}
set
{
// Stroke of luck: both C# and VB legacy code model implementations throw E_NOTIMPL
throw Exceptions.ThrowENotImpl();
}
}
public bool IsPropertyStyleEvent
{
get
{
var node = this.CodeModelService.GetNodeWithModifiers(LookupNode());
return this.CodeModelService.GetIsPropertyStyleEvent(node);
}
}
public EnvDTE.CodeFunction Remover
{
get
{
if (IsPropertyStyleEvent)
{
return CodeAccessorFunction.Create(this.State, this, MethodKind.EventRemove);
}
return null;
}
set
{
// Stroke of luck: both C# and VB legacy code model implementations throw E_NOTIMPL
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.CodeFunction Thrower
{
get
{
if (!CodeModelService.SupportsEventThrower)
{
throw Exceptions.ThrowEFail();
}
if (IsPropertyStyleEvent)
{
return CodeAccessorFunction.Create(this.State, this, MethodKind.EventRaise);
}
return null;
}
set
{
// TODO: C# throws E_FAIL but VB throws E_NOTIMPL.
throw new NotImplementedException();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
return CodeTypeRef.Create(this.State, this, GetProjectId(), EventSymbol.Type);
}
set
{
// The type is sometimes part of the node key, so we should be sure to reacquire
// it after updating it. Note that we pass trackKinds: false because it's possible
// that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function).
UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeEvent))]
public sealed partial class CodeEvent : AbstractCodeMember, EnvDTE80.CodeEvent
{
internal static EnvDTE80.CodeEvent Create(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
{
var element = new CodeEvent(state, fileCodeModel, nodeKey, nodeKind);
var result = (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);
fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result);
return result;
}
internal static EnvDTE80.CodeEvent CreateUnknown(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
{
var element = new CodeEvent(state, fileCodeModel, nodeKind, name);
return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);
}
private CodeEvent(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey,
int? nodeKind)
: base(state, fileCodeModel, nodeKey, nodeKind)
{
}
private CodeEvent(
CodeModelState state,
FileCodeModel fileCodeModel,
int nodeKind,
string name)
: base(state, fileCodeModel, nodeKind, name)
{
}
private IEventSymbol EventSymbol
{
get { return (IEventSymbol)LookupSymbol(); }
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementEvent; }
}
public override EnvDTE.CodeElements Children
{
get { return this.Attributes; }
}
public EnvDTE.CodeFunction Adder
{
get
{
if (IsPropertyStyleEvent)
{
return CodeAccessorFunction.Create(this.State, this, MethodKind.EventAdd);
}
return null;
}
set
{
// Stroke of luck: both C# and VB legacy code model implementations throw E_NOTIMPL
throw Exceptions.ThrowENotImpl();
}
}
public bool IsPropertyStyleEvent
{
get
{
var node = this.CodeModelService.GetNodeWithModifiers(LookupNode());
return this.CodeModelService.GetIsPropertyStyleEvent(node);
}
}
public EnvDTE.CodeFunction Remover
{
get
{
if (IsPropertyStyleEvent)
{
return CodeAccessorFunction.Create(this.State, this, MethodKind.EventRemove);
}
return null;
}
set
{
// Stroke of luck: both C# and VB legacy code model implementations throw E_NOTIMPL
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.CodeFunction Thrower
{
get
{
if (!CodeModelService.SupportsEventThrower)
{
throw Exceptions.ThrowEFail();
}
if (IsPropertyStyleEvent)
{
return CodeAccessorFunction.Create(this.State, this, MethodKind.EventRaise);
}
return null;
}
set
{
// TODO: C# throws E_FAIL but VB throws E_NOTIMPL.
throw new NotImplementedException();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
return CodeTypeRef.Create(this.State, this, GetProjectId(), EventSymbol.Type);
}
set
{
// The type is sometimes part of the node key, so we should be sure to reacquire
// it after updating it. Note that we pass trackKinds: false because it's possible
// that UpdateType might change the kind of a node (e.g. change a VB Sub to a Function).
UpdateNodeAndReacquireNodeKey(FileCodeModel.UpdateType, value, trackKinds: false);
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharp/CommentSelection/CSharpToggleBlockCommentCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.CommentSelection
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.ToggleBlockComment)]
internal class CSharpToggleBlockCommentCommandHandler :
ToggleBlockCommentCommandHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService,
ITextStructureNavigatorSelectorService navigatorSelectorService)
: base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService)
{
}
/// <summary>
/// Retrieves block comments near the selection in the document.
/// Uses the CSharp syntax tree to find the commented spans.
/// </summary>
protected override async Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot,
TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Only search for block comments intersecting the lines in the selections.
return root.DescendantTrivia(linesContainingSelections)
.Where(trivia => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia))
.SelectAsArray(blockCommentTrivia => blockCommentTrivia.Span);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.CommentSelection
{
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.CSharpContentType)]
[Name(PredefinedCommandHandlerNames.ToggleBlockComment)]
internal class CSharpToggleBlockCommentCommandHandler :
ToggleBlockCommentCommandHandler
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService,
ITextStructureNavigatorSelectorService navigatorSelectorService)
: base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService)
{
}
/// <summary>
/// Retrieves block comments near the selection in the document.
/// Uses the CSharp syntax tree to find the commented spans.
/// </summary>
protected override async Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot,
TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Only search for block comments intersecting the lines in the selections.
return root.DescendantTrivia(linesContainingSelections)
.Where(trivia => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineDocumentationCommentTrivia))
.SelectAsArray(blockCommentTrivia => blockCommentTrivia.Span);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Semantic/Semantics/AnonymousFunctionTests.cs |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
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.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[WorkItem(275, "https://github.com/dotnet/csharplang/issues/275")]
[CompilerTrait(CompilerFeature.AnonymousFunctions)]
public class AnonymousFunctionTests : CSharpTestBase
{
public static CSharpCompilation VerifyInPreview(string source, params DiagnosticDescription[] expected)
=> CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(expected);
internal CompilationVerifier VerifyInPreview(CSharpTestSource source, string expectedOutput, Action<ModuleSymbol>? symbolValidator = null, params DiagnosticDescription[] expected)
=> CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.RegularPreview,
symbolValidator: symbolValidator,
expectedOutput: expectedOutput)
.VerifyDiagnostics(expected);
internal void VerifyInPreview(string source, string expectedOutput, string metadataName, string expectedIL)
{
verify(source);
verify(source.Replace("static (", "("));
void verify(string source)
{
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.RegularPreview,
symbolValidator: symbolValidator,
expectedOutput: expectedOutput)
.VerifyDiagnostics();
verifier.VerifyIL(metadataName, expectedIL);
}
void symbolValidator(ModuleSymbol module)
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName);
// note that static anonymous functions do not guarantee that the lowered method will be static.
Assert.False(method.IsStatic);
}
}
[Fact]
public void DisallowInNonPreview()
{
var source = @"
using System;
public class C
{
public static int a;
public void F()
{
Func<int> f = static () => a;
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (10,23): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(10, 23));
}
[Fact]
public void StaticLambdaCanReferenceStaticField()
{
var source = @"
using System;
public class C
{
public static int a;
public static void Main()
{
Func<int> f = static () => a;
a = 42;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__1_0",
expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld ""int C.a""
IL_0005: ret
}
");
}
[Fact]
public void StaticLambdaCanReferenceStaticProperty()
{
var source = @"
using System;
public class C
{
static int A { get; set; }
public static void Main()
{
Func<int> f = static () => A;
A = 42;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__4_0",
expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.A.get""
IL_0005: ret
}");
}
[Fact]
public void StaticLambdaCanReferenceConstField()
{
var source = @"
using System;
public class C
{
public const int a = 42;
public static void Main()
{
Func<int> f = static () => a;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__1_0",
expectedIL: @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: ret
}");
}
[Fact]
public void StaticLambdaCanReferenceConstLocal()
{
var source = @"
using System;
public class C
{
public static void Main()
{
const int a = 42;
Func<int> f = static () => a;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__0_0",
expectedIL: @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: ret
}");
}
[Fact]
public void StaticLambdaCanReturnConstLocal()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
const int a = 42;
return a;
};
Console.Write(f());
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (int V_0)
IL_0000: nop
IL_0001: ldc.i4.s 42
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
}");
}
[Fact]
public void StaticLambdaCannotCaptureInstanceField()
{
var source = @"
using System;
public class C
{
public int a;
public void F()
{
Func<int> f = static () => a;
}
}";
VerifyInPreview(source,
// (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "a").WithLocation(10, 36));
}
[Fact]
public void StaticLambdaCannotCaptureInstanceProperty()
{
var source = @"
using System;
public class C
{
int A { get; }
public void F()
{
Func<int> f = static () => A;
}
}";
VerifyInPreview(source,
// (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// Func<int> f = static () => A;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "A").WithLocation(10, 36));
}
[Fact]
public void StaticLambdaCannotCaptureParameter()
{
var source = @"
using System;
public class C
{
public void F(int a)
{
Func<int> f = static () => a;
}
}";
VerifyInPreview(source,
// (8,36): error CS8427: A static anonymous function cannot contain a reference to 'a'.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(8, 36));
}
[Fact]
public void StaticLambdaCannotCaptureOuterLocal()
{
var source = @"
using System;
public class C
{
public void F()
{
int a;
Func<int> f = static () => a;
}
}";
VerifyInPreview(source,
// (9,36): error CS8427: A static anonymous function cannot contain a reference to 'a'.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(9, 36),
// (9,36): error CS0165: Use of unassigned local variable 'a'
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(9, 36));
}
[Fact]
public void StaticLambdaCanReturnInnerLocal()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
int a = 42;
return a;
};
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__0_0",
expectedIL: @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //a
int V_1)
IL_0000: nop
IL_0001: ldc.i4.s 42
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: stloc.1
IL_0006: br.s IL_0008
IL_0008: ldloc.1
IL_0009: ret
}");
}
[Fact]
public void StaticLambdaCannotReferenceThis()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
this.F();
return 0;
};
}
}";
VerifyInPreview(source,
// (10,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// this.F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(10, 13));
}
[Fact]
public void StaticLambdaCannotReferenceBase()
{
var source = @"
using System;
public class B
{
public virtual void F() { }
}
public class C : B
{
public override void F()
{
Func<int> f = static () =>
{
base.F();
return 0;
};
}
}";
VerifyInPreview(source,
// (15,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// base.F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "base").WithLocation(15, 13));
}
[Fact]
public void StaticLambdaCannotReferenceInstanceLocalFunction()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
F();
return 0;
};
void F() {}
}
}";
VerifyInPreview(source,
// (10,13): error CS8427: A static anonymous function cannot contain a reference to 'F'.
// F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "F()").WithArguments("F").WithLocation(10, 13));
}
[Fact]
public void StaticLambdaCanReferenceStaticLocalFunction()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () => local();
Console.WriteLine(f());
static int local() => 42;
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.<Main>g__local|0_1()""
IL_0005: ret
}");
}
[Fact]
public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLambda()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
int i = 42;
Func<int> g = () => i;
return g();
};
Console.Write(f());
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1, //g
int V_2)
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.s 42
IL_000a: stfld ""int C.<>c__DisplayClass0_0.i""
IL_000f: ldloc.0
IL_0010: ldftn ""int C.<>c__DisplayClass0_0.<Main>b__1()""
IL_0016: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: callvirt ""int System.Func<int>.Invoke()""
IL_0022: stloc.2
IL_0023: br.s IL_0025
IL_0025: ldloc.2
IL_0026: ret
}");
}
[Fact]
public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
int i = 0;
Func<int> g = static () => i;
return 0;
};
}
}";
VerifyInPreview(source,
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = () =>
{
int i = 0;
Func<int> g = static () => i;
return 0;
};
}
}";
VerifyInPreview(source,
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLocalFunction()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
int i = 42;
int g() => i;
return g();
};
Console.Write(f());
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.s 42
IL_0005: stfld ""int C.<>c__DisplayClass0_0.i""
IL_000a: nop
IL_000b: ldloca.s V_0
IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)""
IL_0012: stloc.1
IL_0013: br.s IL_0015
IL_0015: ldloc.1
IL_0016: ret
}");
}
[Fact]
public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = () =>
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLocalFunction()
{
var source = @"
using System;
public class C
{
public static void Main()
{
static int f()
{
int i = 42;
int g() => i;
return g();
};
Console.Write(f());
}
}";
var verifier = VerifyInPreview(
source,
expectedOutput: "42",
symbolValidator);
const string metadataName = "C.<Main>g__f|0_0";
if (RuntimeUtilities.IsCoreClrRuntime)
{
verifier.VerifyIL(metadataName, @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.s 42
IL_0005: stfld ""int C.<>c__DisplayClass0_0.i""
IL_000a: nop
IL_000b: ldloca.s V_0
IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)""
IL_0012: stloc.1
IL_0013: br.s IL_0015
IL_0015: ldloc.1
IL_0016: ret
}");
}
void symbolValidator(ModuleSymbol module)
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName);
Assert.True(method.IsStatic);
}
}
[Fact]
public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
public class C
{
public void F()
{
static int f()
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,20): warning CS8321: The local function 'f' is declared but never used
// static int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20),
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
public class C
{
public void F()
{
int f()
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,13): warning CS8321: The local function 'f' is declared but never used
// int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13),
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
static int f()
{
int i = 0;
Func<int> g = () => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,20): warning CS8321: The local function 'f' is declared but never used
// static int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20));
}
[Fact]
public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
static int f()
{
int i = 0;
Func<int> g = static () => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,20): warning CS8321: The local function 'f' is declared but never used
// static int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20),
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
int f()
{
int i = 0;
Func<int> g = static () => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,13): warning CS8321: The local function 'f' is declared but never used
// int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13),
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void StaticLambdaCanCallStaticMethod()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () => M();
Console.Write(f());
}
static int M() => 42;
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.M()""
IL_0005: ret
}
");
}
[Fact]
public void QueryInStaticLambdaCannotAccessThis()
{
var source = @"
using System;
using System.Linq;
public class C
{
public static string[] args;
public void F()
{
Func<int> f = static () =>
{
var q = from a in args
select M(a);
return 0;
};
}
int M(string a) => 0;
}";
VerifyInPreview(source,
// (14,28): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// select M(a);
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "M").WithLocation(14, 28));
}
[Fact]
public void QueryInStaticLambdaCanReferenceStatic()
{
var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
public class C
{
public static string[] args;
public static void Main()
{
args = new[] { """" };
Func<IEnumerable<int>> f = static () =>
{
var q = from a in args
select M(a);
return q;
};
foreach (var x in f())
{
Console.Write(x);
}
}
static int M(string a) => 42;
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @"
{
// Code size 49 (0x31)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0, //q
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: nop
IL_0001: ldsfld ""string[] C.args""
IL_0006: ldsfld ""System.Func<string, int> C.<>c.<>9__1_1""
IL_000b: dup
IL_000c: brtrue.s IL_0025
IL_000e: pop
IL_000f: ldsfld ""C.<>c C.<>c.<>9""
IL_0014: ldftn ""int C.<>c.<Main>b__1_1(string)""
IL_001a: newobj ""System.Func<string, int>..ctor(object, System.IntPtr)""
IL_001f: dup
IL_0020: stsfld ""System.Func<string, int> C.<>c.<>9__1_1""
IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<string, int>(System.Collections.Generic.IEnumerable<string>, System.Func<string, int>)""
IL_002a: stloc.0
IL_002b: ldloc.0
IL_002c: stloc.1
IL_002d: br.s IL_002f
IL_002f: ldloc.1
IL_0030: ret
}
");
}
[Fact]
public void InstanceLambdaInStaticLambdaCannotReferenceThis()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
Func<int> g = () =>
{
this.F();
return 0;
};
return g();
};
}
}";
VerifyInPreview(source,
// (12,17): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// this.F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(12, 17));
}
[Fact]
public void TestStaticAnonymousFunctions()
{
var source = @"
using System;
public class C
{
public void F()
{
Action<int> a = static delegate(int i) { };
Action<int> b = static a => { };
Action<int> c = static (a) => { };
}
}";
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var root = syntaxTree.GetRoot();
var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single();
var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single();
var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single();
var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!;
var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!;
var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!;
Assert.True(anonymousMethod.IsStatic);
Assert.True(simpleLambda.IsStatic);
Assert.True(parenthesizedLambda.IsStatic);
}
[Fact]
public void TestNonStaticAnonymousFunctions()
{
var source = @"
using System;
public class C
{
public void F()
{
Action<int> a = delegate(int i) { };
Action<int> b = a => { };
Action<int> c = (a) => { };
}
}";
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var root = syntaxTree.GetRoot();
var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single();
var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single();
var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single();
var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!;
var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!;
var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!;
Assert.False(anonymousMethod.IsStatic);
Assert.False(simpleLambda.IsStatic);
Assert.False(parenthesizedLambda.IsStatic);
}
[Fact]
public void TestStaticLambdaCallArgument()
{
var source = @"
using System;
public class C
{
public static void F(Func<string> fn)
{
Console.WriteLine(fn());
}
public static void Main()
{
F(static () => ""hello"");
}
}";
VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr ""hello""
IL_0005: ret
}");
}
[Fact]
public void TestStaticLambdaIndexerArgument()
{
var source = @"
using System;
public class C
{
public object this[Func<object> fn]
{
get
{
Console.WriteLine(fn());
return null;
}
}
public static void Main()
{
_ = new C()[static () => ""hello""];
}
}";
VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__2_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr ""hello""
IL_0005: ret
}");
}
[Fact]
public void TestStaticDelegateCallArgument()
{
var source = @"
using System;
public class C
{
public static void F(Func<string> fn)
{
Console.WriteLine(fn());
}
public static void Main()
{
F(static delegate() { return ""hello""; });
}
}";
VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
}");
}
[Fact]
public void StaticLambdaNameof()
{
var source = @"
using System;
public class C
{
public int w;
public static int x;
public static void F(Func<int, string> fn)
{
Console.WriteLine(fn(0));
}
public static void Main()
{
int y = 0;
F(static (int z) => { return nameof(w) + nameof(x) + nameof(y) + nameof(z); });
}
}";
VerifyInPreview(source, expectedOutput: "wxyz", metadataName: "C.<>c.<Main>b__3_0", expectedIL: @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldstr ""wxyz""
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
}");
}
[Fact]
public void StaticLambdaTypeParams()
{
var source = @"
using System;
public class C<T>
{
public static void F(Func<int, string> fn)
{
Console.WriteLine(fn(0));
}
public static void M<U>()
{
F(static (int x) => { return default(T).ToString() + default(U).ToString(); });
}
}
public class Program
{
public static void Main()
{
C<int>.M<bool>();
}
}";
verify(source);
verify(source.Replace("static (", "("));
void verify(string source)
{
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: symbolValidator,
expectedOutput: "0False")
.VerifyDiagnostics();
verifier.VerifyIL("C<T>.<>c__1<U>.<M>b__1_0", @"
{
// Code size 51 (0x33)
.maxstack 3
.locals init (T V_0,
U V_1,
string V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: dup
IL_0004: initobj ""T""
IL_000a: constrained. ""T""
IL_0010: callvirt ""string object.ToString()""
IL_0015: ldloca.s V_1
IL_0017: dup
IL_0018: initobj ""U""
IL_001e: constrained. ""U""
IL_0024: callvirt ""string object.ToString()""
IL_0029: call ""string string.Concat(string, string)""
IL_002e: stloc.2
IL_002f: br.s IL_0031
IL_0031: ldloc.2
IL_0032: ret
}");
}
void symbolValidator(ModuleSymbol module)
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c__1.<M>b__1_0");
// note that static anonymous functions do not guarantee that the lowered method will be static.
Assert.False(method.IsStatic);
}
}
[Fact]
public void StaticLambda_Nint()
{
var source = @"
using System;
local(static x => x + 1);
void local(Func<nint, nint> fn)
{
Console.WriteLine(fn(0));
}";
VerifyInPreview(source, expectedOutput: "1", metadataName: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + ".<>c.<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">b__0_0", expectedIL: @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: conv.i
IL_0003: add
IL_0004: ret
}");
}
[Fact]
public void StaticLambda_ExpressionTree()
{
var source = @"
using System;
using System.Linq.Expressions;
class C
{
static void Main()
{
local(static x => x + 1);
static void local(Expression<Func<int, int>> fn)
{
Console.WriteLine(fn.Compile()(0));
}
}
}";
var verifier = VerifyInPreview(source, expectedOutput: "1");
verifier.VerifyIL("C.Main", @"
{
// Code size 72 (0x48)
.maxstack 5
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: nop
IL_0001: ldtoken ""int""
IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000b: ldstr ""x""
IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: ldtoken ""int""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_002c: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)""
IL_0031: ldc.i4.1
IL_0032: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0037: dup
IL_0038: ldc.i4.0
IL_0039: ldloc.0
IL_003a: stelem.ref
IL_003b: call ""System.Linq.Expressions.Expression<System.Func<int, int>> System.Linq.Expressions.Expression.Lambda<System.Func<int, int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0040: call ""void C.<Main>g__local|0_1(System.Linq.Expressions.Expression<System.Func<int, int>>)""
IL_0045: nop
IL_0046: nop
IL_0047: ret
}");
}
[Fact]
public void StaticLambda_FunctionPointer_01()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = &static () => { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,32): error CS1525: Invalid expression term 'static'
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "static").WithArguments("static").WithLocation(6, 32),
// (6,32): error CS1002: ; expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "static").WithLocation(6, 32),
// (6,32): error CS0106: The modifier 'static' is not valid for this item
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 32),
// (6,40): error CS8124: Tuple must contain at least two elements.
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(6, 40),
// (6,42): error CS1001: Identifier expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_IdentifierExpected, "=>").WithLocation(6, 42),
// (6,42): error CS1003: Syntax error, ',' expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 42),
// (6,45): error CS1002: ; expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 45)
);
}
[Fact]
public void StaticLambda_FunctionPointer_02()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = static () => { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,31): error CS1660: Cannot convert lambda expression to type 'delegate*<void>' because it is not a delegate type
// delegate*<void> ptr = static () => { };
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static () => { }").WithArguments("lambda expression", "delegate*<void>").WithLocation(6, 31)
);
}
[Fact]
public void StaticAnonymousMethod_FunctionPointer_01()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = &static delegate() { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,32): error CS0211: Cannot take the address of the given expression
// delegate*<void> ptr = &static delegate() { };
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "static delegate() { }").WithLocation(6, 32)
);
}
[Fact]
public void StaticAnonymousMethod_FunctionPointer_02()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = static delegate() { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,31): error CS1660: Cannot convert anonymous method to type 'delegate*<void>' because it is not a delegate type
// delegate*<void> ptr = static delegate() { };
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static delegate() { }").WithArguments("anonymous method", "delegate*<void>").WithLocation(6, 31)
);
}
[Fact]
public void ConditionalExpr()
{
var source = @"
using static System.Console;
class C
{
static void M(bool b, System.Action a)
{
a = b ? () => Write(1) : a;
a();
a = b ? static () => Write(2) : a;
a();
a = b ? () => { Write(3); } : a;
a();
a = b ? static () => { Write(4); } : a;
a();
a = b ? a : () => { };
a = b ? a : static () => { };
a = b ? delegate() { Write(5); } : a;
a();
a = b ? static delegate() { Write(6); } : a;
a();
a = b ? a : delegate() { };
a = b ? a : static delegate() { };
}
static void Main()
{
M(true, () => { });
}
}
";
CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9);
}
[Fact]
public void RefConditionalExpr()
{
var source = @"
using static System.Console;
class C
{
static void M(bool b, ref System.Action a)
{
a = ref b ? ref () => Write(1) : ref a;
a();
a = ref b ? ref static () => Write(2) : ref a;
a();
a = ref b ? ref () => { Write(3); } : ref a;
a();
a = ref b ? ref static () => { Write(4); } : ref a;
a();
a = ref b ? ref a : ref () => { };
a = ref b ? ref a : ref static () => { };
a = ref b ? ref delegate() { Write(5); } : ref a;
a();
a = ref b ? ref static delegate() { Write(6); } : ref a;
a();
a = ref b ? ref a : ref delegate() { };
a = b ? ref a : ref static delegate() { };
}
}
";
VerifyInPreview(source,
// (8,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref () => Write(1) : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => Write(1)").WithLocation(8, 25),
// (11,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref static () => Write(2) : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => Write(2)").WithLocation(11, 25),
// (14,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref () => { Write(3); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { Write(3); }").WithLocation(14, 25),
// (17,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref static () => { Write(4); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { Write(4); }").WithLocation(17, 25),
// (20,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref a : ref () => { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { }").WithLocation(20, 33),
// (21,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref a : ref static () => { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { }").WithLocation(21, 33),
// (23,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref delegate() { Write(5); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { Write(5); }").WithLocation(23, 25),
// (26,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref static delegate() { Write(6); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { Write(6); }").WithLocation(26, 25),
// (29,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref a : ref delegate() { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { }").WithLocation(29, 33),
// (30,29): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = b ? ref a : ref static delegate() { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { }").WithLocation(30, 29)
);
}
[Fact]
public void SwitchExpr()
{
var source = @"
using static System.Console;
class C
{
static void M(bool b, System.Action a)
{
a = b switch { true => () => Write(1), false => a };
a();
a = b switch { true => static () => Write(2), false => a };
a();
a = b switch { true => () => { Write(3); }, false => a };
a();
a = b switch { true => static () => { Write(4); }, false => a };
a();
a = b switch { true => a , false => () => { Write(0); } };
a = b switch { true => a , false => static () => { Write(0); } };
a = b switch { true => delegate() { Write(5); }, false => a };
a();
a = b switch { true => static delegate() { Write(6); }, false => a };
a();
a = b switch { true => a , false => delegate() { Write(0); } };
a = b switch { true => a , false => static delegate() { Write(0); } };
}
static void Main()
{
M(true, () => { });
}
}
";
CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9);
}
[Fact]
public void DiscardParams()
{
var source = @"
using System;
class C
{
static void Main()
{
Action<int, int, string> fn = static (_, _, z) => Console.Write(z);
fn(1, 2, ""hello"");
fn = static delegate(int _, int _, string z) { Console.Write(z); };
fn(3, 4, "" world"");
}
}
";
CompileAndVerify(source, expectedOutput: "hello world", parseOptions: TestOptions.Regular9);
}
[Fact]
public void PrivateMemberAccessibility()
{
var source = @"
using System;
class C
{
private static void M1(int i) { Console.Write(i); }
class Inner
{
static void Main()
{
Action a = static () => M1(1);
a();
a = static delegate() { M1(2); };
a();
}
}
}
";
verify(source);
verify(source.Replace("static (", "("));
void verify(string source)
{
CompileAndVerify(source, expectedOutput: "12", parseOptions: TestOptions.Regular9);
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
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.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
[WorkItem(275, "https://github.com/dotnet/csharplang/issues/275")]
[CompilerTrait(CompilerFeature.AnonymousFunctions)]
public class AnonymousFunctionTests : CSharpTestBase
{
public static CSharpCompilation VerifyInPreview(string source, params DiagnosticDescription[] expected)
=> CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(expected);
internal CompilationVerifier VerifyInPreview(CSharpTestSource source, string expectedOutput, Action<ModuleSymbol>? symbolValidator = null, params DiagnosticDescription[] expected)
=> CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.RegularPreview,
symbolValidator: symbolValidator,
expectedOutput: expectedOutput)
.VerifyDiagnostics(expected);
internal void VerifyInPreview(string source, string expectedOutput, string metadataName, string expectedIL)
{
verify(source);
verify(source.Replace("static (", "("));
void verify(string source)
{
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.RegularPreview,
symbolValidator: symbolValidator,
expectedOutput: expectedOutput)
.VerifyDiagnostics();
verifier.VerifyIL(metadataName, expectedIL);
}
void symbolValidator(ModuleSymbol module)
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName);
// note that static anonymous functions do not guarantee that the lowered method will be static.
Assert.False(method.IsStatic);
}
}
[Fact]
public void DisallowInNonPreview()
{
var source = @"
using System;
public class C
{
public static int a;
public void F()
{
Func<int> f = static () => a;
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (10,23): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(10, 23));
}
[Fact]
public void StaticLambdaCanReferenceStaticField()
{
var source = @"
using System;
public class C
{
public static int a;
public static void Main()
{
Func<int> f = static () => a;
a = 42;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__1_0",
expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld ""int C.a""
IL_0005: ret
}
");
}
[Fact]
public void StaticLambdaCanReferenceStaticProperty()
{
var source = @"
using System;
public class C
{
static int A { get; set; }
public static void Main()
{
Func<int> f = static () => A;
A = 42;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__4_0",
expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.A.get""
IL_0005: ret
}");
}
[Fact]
public void StaticLambdaCanReferenceConstField()
{
var source = @"
using System;
public class C
{
public const int a = 42;
public static void Main()
{
Func<int> f = static () => a;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__1_0",
expectedIL: @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: ret
}");
}
[Fact]
public void StaticLambdaCanReferenceConstLocal()
{
var source = @"
using System;
public class C
{
public static void Main()
{
const int a = 42;
Func<int> f = static () => a;
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__0_0",
expectedIL: @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: ret
}");
}
[Fact]
public void StaticLambdaCanReturnConstLocal()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
const int a = 42;
return a;
};
Console.Write(f());
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (int V_0)
IL_0000: nop
IL_0001: ldc.i4.s 42
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
}");
}
[Fact]
public void StaticLambdaCannotCaptureInstanceField()
{
var source = @"
using System;
public class C
{
public int a;
public void F()
{
Func<int> f = static () => a;
}
}";
VerifyInPreview(source,
// (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "a").WithLocation(10, 36));
}
[Fact]
public void StaticLambdaCannotCaptureInstanceProperty()
{
var source = @"
using System;
public class C
{
int A { get; }
public void F()
{
Func<int> f = static () => A;
}
}";
VerifyInPreview(source,
// (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// Func<int> f = static () => A;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "A").WithLocation(10, 36));
}
[Fact]
public void StaticLambdaCannotCaptureParameter()
{
var source = @"
using System;
public class C
{
public void F(int a)
{
Func<int> f = static () => a;
}
}";
VerifyInPreview(source,
// (8,36): error CS8427: A static anonymous function cannot contain a reference to 'a'.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(8, 36));
}
[Fact]
public void StaticLambdaCannotCaptureOuterLocal()
{
var source = @"
using System;
public class C
{
public void F()
{
int a;
Func<int> f = static () => a;
}
}";
VerifyInPreview(source,
// (9,36): error CS8427: A static anonymous function cannot contain a reference to 'a'.
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(9, 36),
// (9,36): error CS0165: Use of unassigned local variable 'a'
// Func<int> f = static () => a;
Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(9, 36));
}
[Fact]
public void StaticLambdaCanReturnInnerLocal()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
int a = 42;
return a;
};
Console.Write(f());
}
}";
VerifyInPreview(
source,
expectedOutput: "42",
metadataName: "C.<>c.<Main>b__0_0",
expectedIL: @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //a
int V_1)
IL_0000: nop
IL_0001: ldc.i4.s 42
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: stloc.1
IL_0006: br.s IL_0008
IL_0008: ldloc.1
IL_0009: ret
}");
}
[Fact]
public void StaticLambdaCannotReferenceThis()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
this.F();
return 0;
};
}
}";
VerifyInPreview(source,
// (10,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// this.F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(10, 13));
}
[Fact]
public void StaticLambdaCannotReferenceBase()
{
var source = @"
using System;
public class B
{
public virtual void F() { }
}
public class C : B
{
public override void F()
{
Func<int> f = static () =>
{
base.F();
return 0;
};
}
}";
VerifyInPreview(source,
// (15,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// base.F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "base").WithLocation(15, 13));
}
[Fact]
public void StaticLambdaCannotReferenceInstanceLocalFunction()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
F();
return 0;
};
void F() {}
}
}";
VerifyInPreview(source,
// (10,13): error CS8427: A static anonymous function cannot contain a reference to 'F'.
// F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "F()").WithArguments("F").WithLocation(10, 13));
}
[Fact]
public void StaticLambdaCanReferenceStaticLocalFunction()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () => local();
Console.WriteLine(f());
static int local() => 42;
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.<Main>g__local|0_1()""
IL_0005: ret
}");
}
[Fact]
public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLambda()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
int i = 42;
Func<int> g = () => i;
return g();
};
Console.Write(f());
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1, //g
int V_2)
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.s 42
IL_000a: stfld ""int C.<>c__DisplayClass0_0.i""
IL_000f: ldloc.0
IL_0010: ldftn ""int C.<>c__DisplayClass0_0.<Main>b__1()""
IL_0016: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: callvirt ""int System.Func<int>.Invoke()""
IL_0022: stloc.2
IL_0023: br.s IL_0025
IL_0025: ldloc.2
IL_0026: ret
}");
}
[Fact]
public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
int i = 0;
Func<int> g = static () => i;
return 0;
};
}
}";
VerifyInPreview(source,
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = () =>
{
int i = 0;
Func<int> g = static () => i;
return 0;
};
}
}";
VerifyInPreview(source,
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLocalFunction()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () =>
{
int i = 42;
int g() => i;
return g();
};
Console.Write(f());
}
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.s 42
IL_0005: stfld ""int C.<>c__DisplayClass0_0.i""
IL_000a: nop
IL_000b: ldloca.s V_0
IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)""
IL_0012: stloc.1
IL_0013: br.s IL_0015
IL_0015: ldloc.1
IL_0016: ret
}");
}
[Fact]
public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = () =>
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLocalFunction()
{
var source = @"
using System;
public class C
{
public static void Main()
{
static int f()
{
int i = 42;
int g() => i;
return g();
};
Console.Write(f());
}
}";
var verifier = VerifyInPreview(
source,
expectedOutput: "42",
symbolValidator);
const string metadataName = "C.<Main>g__f|0_0";
if (RuntimeUtilities.IsCoreClrRuntime)
{
verifier.VerifyIL(metadataName, @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.s 42
IL_0005: stfld ""int C.<>c__DisplayClass0_0.i""
IL_000a: nop
IL_000b: ldloca.s V_0
IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)""
IL_0012: stloc.1
IL_0013: br.s IL_0015
IL_0015: ldloc.1
IL_0016: ret
}");
}
void symbolValidator(ModuleSymbol module)
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName);
Assert.True(method.IsStatic);
}
}
[Fact]
public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
public class C
{
public void F()
{
static int f()
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,20): warning CS8321: The local function 'f' is declared but never used
// static int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20),
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction()
{
var source = @"
public class C
{
public void F()
{
int f()
{
int i = 0;
static int g() => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,13): warning CS8321: The local function 'f' is declared but never used
// int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13),
// (11,31): error CS8421: A static local function cannot contain a reference to 'i'.
// static int g() => i;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31));
}
[Fact]
public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
static int f()
{
int i = 0;
Func<int> g = () => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,20): warning CS8321: The local function 'f' is declared but never used
// static int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20));
}
[Fact]
public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
static int f()
{
int i = 0;
Func<int> g = static () => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,20): warning CS8321: The local function 'f' is declared but never used
// static int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20),
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda()
{
var source = @"
using System;
public class C
{
public void F()
{
int f()
{
int i = 0;
Func<int> g = static () => i;
return g();
};
}
}";
VerifyInPreview(source,
// (8,13): warning CS8321: The local function 'f' is declared but never used
// int f()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13),
// (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'.
// Func<int> g = static () => i;
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40));
}
[Fact]
public void StaticLambdaCanCallStaticMethod()
{
var source = @"
using System;
public class C
{
public static void Main()
{
Func<int> f = static () => M();
Console.Write(f());
}
static int M() => 42;
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: call ""int C.M()""
IL_0005: ret
}
");
}
[Fact]
public void QueryInStaticLambdaCannotAccessThis()
{
var source = @"
using System;
using System.Linq;
public class C
{
public static string[] args;
public void F()
{
Func<int> f = static () =>
{
var q = from a in args
select M(a);
return 0;
};
}
int M(string a) => 0;
}";
VerifyInPreview(source,
// (14,28): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// select M(a);
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "M").WithLocation(14, 28));
}
[Fact]
public void QueryInStaticLambdaCanReferenceStatic()
{
var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
public class C
{
public static string[] args;
public static void Main()
{
args = new[] { """" };
Func<IEnumerable<int>> f = static () =>
{
var q = from a in args
select M(a);
return q;
};
foreach (var x in f())
{
Console.Write(x);
}
}
static int M(string a) => 42;
}";
VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @"
{
// Code size 49 (0x31)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0, //q
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: nop
IL_0001: ldsfld ""string[] C.args""
IL_0006: ldsfld ""System.Func<string, int> C.<>c.<>9__1_1""
IL_000b: dup
IL_000c: brtrue.s IL_0025
IL_000e: pop
IL_000f: ldsfld ""C.<>c C.<>c.<>9""
IL_0014: ldftn ""int C.<>c.<Main>b__1_1(string)""
IL_001a: newobj ""System.Func<string, int>..ctor(object, System.IntPtr)""
IL_001f: dup
IL_0020: stsfld ""System.Func<string, int> C.<>c.<>9__1_1""
IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<string, int>(System.Collections.Generic.IEnumerable<string>, System.Func<string, int>)""
IL_002a: stloc.0
IL_002b: ldloc.0
IL_002c: stloc.1
IL_002d: br.s IL_002f
IL_002f: ldloc.1
IL_0030: ret
}
");
}
[Fact]
public void InstanceLambdaInStaticLambdaCannotReferenceThis()
{
var source = @"
using System;
public class C
{
public void F()
{
Func<int> f = static () =>
{
Func<int> g = () =>
{
this.F();
return 0;
};
return g();
};
}
}";
VerifyInPreview(source,
// (12,17): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'.
// this.F();
Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(12, 17));
}
[Fact]
public void TestStaticAnonymousFunctions()
{
var source = @"
using System;
public class C
{
public void F()
{
Action<int> a = static delegate(int i) { };
Action<int> b = static a => { };
Action<int> c = static (a) => { };
}
}";
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var root = syntaxTree.GetRoot();
var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single();
var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single();
var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single();
var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!;
var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!;
var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!;
Assert.True(anonymousMethod.IsStatic);
Assert.True(simpleLambda.IsStatic);
Assert.True(parenthesizedLambda.IsStatic);
}
[Fact]
public void TestNonStaticAnonymousFunctions()
{
var source = @"
using System;
public class C
{
public void F()
{
Action<int> a = delegate(int i) { };
Action<int> b = a => { };
Action<int> c = (a) => { };
}
}";
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var root = syntaxTree.GetRoot();
var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single();
var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single();
var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single();
var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!;
var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!;
var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!;
Assert.False(anonymousMethod.IsStatic);
Assert.False(simpleLambda.IsStatic);
Assert.False(parenthesizedLambda.IsStatic);
}
[Fact]
public void TestStaticLambdaCallArgument()
{
var source = @"
using System;
public class C
{
public static void F(Func<string> fn)
{
Console.WriteLine(fn());
}
public static void Main()
{
F(static () => ""hello"");
}
}";
VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr ""hello""
IL_0005: ret
}");
}
[Fact]
public void TestStaticLambdaIndexerArgument()
{
var source = @"
using System;
public class C
{
public object this[Func<object> fn]
{
get
{
Console.WriteLine(fn());
return null;
}
}
public static void Main()
{
_ = new C()[static () => ""hello""];
}
}";
VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__2_0", expectedIL: @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldstr ""hello""
IL_0005: ret
}");
}
[Fact]
public void TestStaticDelegateCallArgument()
{
var source = @"
using System;
public class C
{
public static void F(Func<string> fn)
{
Console.WriteLine(fn());
}
public static void Main()
{
F(static delegate() { return ""hello""; });
}
}";
VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
}");
}
[Fact]
public void StaticLambdaNameof()
{
var source = @"
using System;
public class C
{
public int w;
public static int x;
public static void F(Func<int, string> fn)
{
Console.WriteLine(fn(0));
}
public static void Main()
{
int y = 0;
F(static (int z) => { return nameof(w) + nameof(x) + nameof(y) + nameof(z); });
}
}";
VerifyInPreview(source, expectedOutput: "wxyz", metadataName: "C.<>c.<Main>b__3_0", expectedIL: @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (string V_0)
IL_0000: nop
IL_0001: ldstr ""wxyz""
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
}");
}
[Fact]
public void StaticLambdaTypeParams()
{
var source = @"
using System;
public class C<T>
{
public static void F(Func<int, string> fn)
{
Console.WriteLine(fn(0));
}
public static void M<U>()
{
F(static (int x) => { return default(T).ToString() + default(U).ToString(); });
}
}
public class Program
{
public static void Main()
{
C<int>.M<bool>();
}
}";
verify(source);
verify(source.Replace("static (", "("));
void verify(string source)
{
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: symbolValidator,
expectedOutput: "0False")
.VerifyDiagnostics();
verifier.VerifyIL("C<T>.<>c__1<U>.<M>b__1_0", @"
{
// Code size 51 (0x33)
.maxstack 3
.locals init (T V_0,
U V_1,
string V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: dup
IL_0004: initobj ""T""
IL_000a: constrained. ""T""
IL_0010: callvirt ""string object.ToString()""
IL_0015: ldloca.s V_1
IL_0017: dup
IL_0018: initobj ""U""
IL_001e: constrained. ""U""
IL_0024: callvirt ""string object.ToString()""
IL_0029: call ""string string.Concat(string, string)""
IL_002e: stloc.2
IL_002f: br.s IL_0031
IL_0031: ldloc.2
IL_0032: ret
}");
}
void symbolValidator(ModuleSymbol module)
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c__1.<M>b__1_0");
// note that static anonymous functions do not guarantee that the lowered method will be static.
Assert.False(method.IsStatic);
}
}
[Fact]
public void StaticLambda_Nint()
{
var source = @"
using System;
local(static x => x + 1);
void local(Func<nint, nint> fn)
{
Console.WriteLine(fn(0));
}";
VerifyInPreview(source, expectedOutput: "1", metadataName: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + ".<>c.<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">b__0_0", expectedIL: @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: conv.i
IL_0003: add
IL_0004: ret
}");
}
[Fact]
public void StaticLambda_ExpressionTree()
{
var source = @"
using System;
using System.Linq.Expressions;
class C
{
static void Main()
{
local(static x => x + 1);
static void local(Expression<Func<int, int>> fn)
{
Console.WriteLine(fn.Compile()(0));
}
}
}";
var verifier = VerifyInPreview(source, expectedOutput: "1");
verifier.VerifyIL("C.Main", @"
{
// Code size 72 (0x48)
.maxstack 5
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: nop
IL_0001: ldtoken ""int""
IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000b: ldstr ""x""
IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: ldtoken ""int""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_002c: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)""
IL_0031: ldc.i4.1
IL_0032: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0037: dup
IL_0038: ldc.i4.0
IL_0039: ldloc.0
IL_003a: stelem.ref
IL_003b: call ""System.Linq.Expressions.Expression<System.Func<int, int>> System.Linq.Expressions.Expression.Lambda<System.Func<int, int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0040: call ""void C.<Main>g__local|0_1(System.Linq.Expressions.Expression<System.Func<int, int>>)""
IL_0045: nop
IL_0046: nop
IL_0047: ret
}");
}
[Fact]
public void StaticLambda_FunctionPointer_01()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = &static () => { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,32): error CS1525: Invalid expression term 'static'
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "static").WithArguments("static").WithLocation(6, 32),
// (6,32): error CS1002: ; expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "static").WithLocation(6, 32),
// (6,32): error CS0106: The modifier 'static' is not valid for this item
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 32),
// (6,40): error CS8124: Tuple must contain at least two elements.
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(6, 40),
// (6,42): error CS1001: Identifier expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_IdentifierExpected, "=>").WithLocation(6, 42),
// (6,42): error CS1003: Syntax error, ',' expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 42),
// (6,45): error CS1002: ; expected
// delegate*<void> ptr = &static () => { };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 45)
);
}
[Fact]
public void StaticLambda_FunctionPointer_02()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = static () => { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,31): error CS1660: Cannot convert lambda expression to type 'delegate*<void>' because it is not a delegate type
// delegate*<void> ptr = static () => { };
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static () => { }").WithArguments("lambda expression", "delegate*<void>").WithLocation(6, 31)
);
}
[Fact]
public void StaticAnonymousMethod_FunctionPointer_01()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = &static delegate() { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,32): error CS0211: Cannot take the address of the given expression
// delegate*<void> ptr = &static delegate() { };
Diagnostic(ErrorCode.ERR_InvalidAddrOp, "static delegate() { }").WithLocation(6, 32)
);
}
[Fact]
public void StaticAnonymousMethod_FunctionPointer_02()
{
var source = @"
class C
{
unsafe void M()
{
delegate*<void> ptr = static delegate() { };
ptr();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,31): error CS1660: Cannot convert anonymous method to type 'delegate*<void>' because it is not a delegate type
// delegate*<void> ptr = static delegate() { };
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static delegate() { }").WithArguments("anonymous method", "delegate*<void>").WithLocation(6, 31)
);
}
[Fact]
public void ConditionalExpr()
{
var source = @"
using static System.Console;
class C
{
static void M(bool b, System.Action a)
{
a = b ? () => Write(1) : a;
a();
a = b ? static () => Write(2) : a;
a();
a = b ? () => { Write(3); } : a;
a();
a = b ? static () => { Write(4); } : a;
a();
a = b ? a : () => { };
a = b ? a : static () => { };
a = b ? delegate() { Write(5); } : a;
a();
a = b ? static delegate() { Write(6); } : a;
a();
a = b ? a : delegate() { };
a = b ? a : static delegate() { };
}
static void Main()
{
M(true, () => { });
}
}
";
CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9);
}
[Fact]
public void RefConditionalExpr()
{
var source = @"
using static System.Console;
class C
{
static void M(bool b, ref System.Action a)
{
a = ref b ? ref () => Write(1) : ref a;
a();
a = ref b ? ref static () => Write(2) : ref a;
a();
a = ref b ? ref () => { Write(3); } : ref a;
a();
a = ref b ? ref static () => { Write(4); } : ref a;
a();
a = ref b ? ref a : ref () => { };
a = ref b ? ref a : ref static () => { };
a = ref b ? ref delegate() { Write(5); } : ref a;
a();
a = ref b ? ref static delegate() { Write(6); } : ref a;
a();
a = ref b ? ref a : ref delegate() { };
a = b ? ref a : ref static delegate() { };
}
}
";
VerifyInPreview(source,
// (8,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref () => Write(1) : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => Write(1)").WithLocation(8, 25),
// (11,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref static () => Write(2) : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => Write(2)").WithLocation(11, 25),
// (14,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref () => { Write(3); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { Write(3); }").WithLocation(14, 25),
// (17,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref static () => { Write(4); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { Write(4); }").WithLocation(17, 25),
// (20,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref a : ref () => { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { }").WithLocation(20, 33),
// (21,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref a : ref static () => { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { }").WithLocation(21, 33),
// (23,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref delegate() { Write(5); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { Write(5); }").WithLocation(23, 25),
// (26,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref static delegate() { Write(6); } : ref a;
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { Write(6); }").WithLocation(26, 25),
// (29,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = ref b ? ref a : ref delegate() { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { }").WithLocation(29, 33),
// (30,29): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// a = b ? ref a : ref static delegate() { };
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { }").WithLocation(30, 29)
);
}
[Fact]
public void SwitchExpr()
{
var source = @"
using static System.Console;
class C
{
static void M(bool b, System.Action a)
{
a = b switch { true => () => Write(1), false => a };
a();
a = b switch { true => static () => Write(2), false => a };
a();
a = b switch { true => () => { Write(3); }, false => a };
a();
a = b switch { true => static () => { Write(4); }, false => a };
a();
a = b switch { true => a , false => () => { Write(0); } };
a = b switch { true => a , false => static () => { Write(0); } };
a = b switch { true => delegate() { Write(5); }, false => a };
a();
a = b switch { true => static delegate() { Write(6); }, false => a };
a();
a = b switch { true => a , false => delegate() { Write(0); } };
a = b switch { true => a , false => static delegate() { Write(0); } };
}
static void Main()
{
M(true, () => { });
}
}
";
CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9);
}
[Fact]
public void DiscardParams()
{
var source = @"
using System;
class C
{
static void Main()
{
Action<int, int, string> fn = static (_, _, z) => Console.Write(z);
fn(1, 2, ""hello"");
fn = static delegate(int _, int _, string z) { Console.Write(z); };
fn(3, 4, "" world"");
}
}
";
CompileAndVerify(source, expectedOutput: "hello world", parseOptions: TestOptions.Regular9);
}
[Fact]
public void PrivateMemberAccessibility()
{
var source = @"
using System;
class C
{
private static void M1(int i) { Console.Write(i); }
class Inner
{
static void Main()
{
Action a = static () => M1(1);
a();
a = static delegate() { M1(2); };
a();
}
}
}
";
verify(source);
verify(source.Replace("static (", "("));
void verify(string source)
{
CompileAndVerify(source, expectedOutput: "12", parseOptions: TestOptions.Regular9);
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// An abstract flow pass that takes some shortcuts in analyzing finally blocks, in order to enable
/// the analysis to take place without tracking exceptions or repeating the analysis of a finally block
/// for each exit from a try statement. The shortcut results in a slightly less precise
/// (but still conservative) analysis, but that less precise analysis is all that is required for
/// the language specification. The most significant shortcut is that we do not track the state
/// where exceptions can arise. That does not affect the soundness for most analyses, but for those
/// analyses whose soundness would be affected (e.g. "data flows out"), we track "unassignments" to keep
/// the analysis sound.
/// </summary>
/// <remarks>
/// Formally, this is a fairly conventional lattice flow analysis (<see
/// href="https://en.wikipedia.org/wiki/Data-flow_analysis"/>) that moves upward through the <see cref="Join(ref
/// TLocalState, ref TLocalState)"/> operation.
/// </remarks>
internal abstract partial class AbstractFlowPass<TLocalState, TLocalFunctionState> : BoundTreeVisitor
where TLocalState : AbstractFlowPass<TLocalState, TLocalFunctionState>.ILocalState
where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState
{
protected int _recursionDepth;
/// <summary>
/// The compilation in which the analysis is taking place. This is needed to determine which
/// conditional methods will be compiled and which will be omitted.
/// </summary>
protected readonly CSharpCompilation compilation;
/// <summary>
/// The method whose body is being analyzed, or the field whose initializer is being analyzed.
/// May be a top-level member or a lambda or local function. It is used for
/// references to method parameters. Thus, '_symbol' should not be used directly, but
/// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used
/// instead. _symbol is null during speculative binding.
/// </summary>
protected readonly Symbol _symbol;
/// <summary>
/// Reflects the enclosing member, lambda or local function at the current location (in the bound tree).
/// </summary>
protected Symbol CurrentSymbol;
/// <summary>
/// The bound node of the method or initializer being analyzed.
/// </summary>
protected readonly BoundNode methodMainNode;
/// <summary>
/// The flow analysis state at each label, computed by calling <see cref="Join(ref
/// TLocalState, ref TLocalState)"/> on the state from branches to that label with the state
/// when we fall into the label. Entries are created when the label is encountered. One
/// case deserves special attention: when the destination of the branch is a label earlier
/// in the code, it is possible (though rarely occurs in practice) that we are changing the
/// state at a label that we've already analyzed. In that case we run another pass of the
/// analysis to allow those changes to propagate. This repeats until no further changes to
/// the state of these labels occurs. This can result in quadratic performance in unlikely
/// but possible code such as this: "int x; if (cond) goto l1; x = 3; l5: print x; l4: goto
/// l5; l3: goto l4; l2: goto l3; l1: goto l2;"
/// </summary>
private readonly PooledDictionary<LabelSymbol, TLocalState> _labels;
/// <summary>
/// Set to true after an analysis scan if the analysis was incomplete due to state changing
/// after it was used by another analysis component. In this case the caller scans again (until
/// this is false). Since the analysis proceeds by monotonically changing the state computed
/// at each label, this must terminate.
/// </summary>
protected bool stateChangedAfterUse;
/// <summary>
/// All of the labels seen so far in this forward scan of the body
/// </summary>
private PooledHashSet<BoundStatement> _labelsSeen;
/// <summary>
/// Pending escapes generated in the current scope (or more deeply nested scopes). When jump
/// statements (goto, break, continue, return) are processed, they are placed in the
/// pendingBranches buffer to be processed later by the code handling the destination
/// statement. As a special case, the processing of try-finally statements might modify the
/// contents of the pendingBranches buffer to take into account the behavior of
/// "intervening" finally clauses.
/// </summary>
protected ArrayBuilder<PendingBranch> PendingBranches { get; private set; }
/// <summary>
/// The definite assignment and/or reachability state at the point currently being analyzed.
/// </summary>
protected TLocalState State;
protected TLocalState StateWhenTrue;
protected TLocalState StateWhenFalse;
protected bool IsConditionalState;
/// <summary>
/// Indicates that the transfer function for a particular node (the function mapping the
/// state before the node to the state after the node) is not monotonic, in the sense that
/// it can change the state in either direction in the lattice. If the transfer function is
/// monotonic, the transfer function can only change the state toward the <see
/// cref="UnreachableState"/>. Reachability and definite assignment are monotonic, and
/// permit a more efficient analysis. Region analysis and nullable analysis are not
/// monotonic. This is just an optimization; we could treat all of them as nonmonotonic
/// without much loss of performance. In fact, this only affects the analysis of (relatively
/// rare) try statements, and is only a slight optimization.
/// </summary>
private readonly bool _nonMonotonicTransfer;
protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state)
{
SetConditionalState(state.whenTrue, state.whenFalse);
}
protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse)
{
IsConditionalState = true;
State = default(TLocalState);
StateWhenTrue = whenTrue;
StateWhenFalse = whenFalse;
}
protected void SetState(TLocalState newState)
{
Debug.Assert(newState != null);
StateWhenTrue = StateWhenFalse = default(TLocalState);
IsConditionalState = false;
State = newState;
}
protected void Split()
{
if (!IsConditionalState)
{
SetConditionalState(State, State.Clone());
}
}
protected void Unsplit()
{
if (IsConditionalState)
{
Join(ref StateWhenTrue, ref StateWhenFalse);
SetState(StateWhenTrue);
}
}
/// <summary>
/// Where all diagnostics are deposited.
/// </summary>
protected DiagnosticBag Diagnostics { get; }
#region Region
// For region analysis, we maintain some extra data.
protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region
protected readonly BoundNode firstInRegion, lastInRegion;
protected readonly bool TrackingRegions;
/// <summary>
/// A cache of the state at the backward branch point of each loop. This is not needed
/// during normal flow analysis, but is needed for DataFlowsOut region analysis.
/// </summary>
private readonly Dictionary<BoundLoopStatement, TLocalState> _loopHeadState;
#endregion Region
protected AbstractFlowPass(
CSharpCompilation compilation,
Symbol symbol,
BoundNode node,
BoundNode firstInRegion = null,
BoundNode lastInRegion = null,
bool trackRegions = false,
bool nonMonotonicTransferFunction = false)
{
Debug.Assert(node != null);
if (firstInRegion != null && lastInRegion != null)
{
trackRegions = true;
}
if (trackRegions)
{
Debug.Assert(firstInRegion != null);
Debug.Assert(lastInRegion != null);
int startLocation = firstInRegion.Syntax.SpanStart;
int endLocation = lastInRegion.Syntax.Span.End;
int length = endLocation - startLocation;
Debug.Assert(length >= 0, "last comes before first");
this.RegionSpan = new TextSpan(startLocation, length);
}
PendingBranches = ArrayBuilder<PendingBranch>.GetInstance();
_labelsSeen = PooledHashSet<BoundStatement>.GetInstance();
_labels = PooledDictionary<LabelSymbol, TLocalState>.GetInstance();
this.Diagnostics = DiagnosticBag.GetInstance();
this.compilation = compilation;
_symbol = symbol;
CurrentSymbol = symbol;
this.methodMainNode = node;
this.firstInRegion = firstInRegion;
this.lastInRegion = lastInRegion;
_loopHeadState = new Dictionary<BoundLoopStatement, TLocalState>(ReferenceEqualityComparer.Instance);
TrackingRegions = trackRegions;
_nonMonotonicTransfer = nonMonotonicTransferFunction;
}
protected abstract string Dump(TLocalState state);
protected string Dump()
{
return IsConditionalState
? $"true: {Dump(this.StateWhenTrue)} false: {Dump(this.StateWhenFalse)}"
: Dump(this.State);
}
#if DEBUG
protected string DumpLabels()
{
StringBuilder result = new StringBuilder();
result.Append("Labels{");
bool first = true;
foreach (var key in _labels.Keys)
{
if (!first)
{
result.Append(", ");
}
string name = key.Name;
if (string.IsNullOrEmpty(name))
{
name = "<Label>" + key.GetHashCode();
}
result.Append(name).Append(": ").Append(this.Dump(_labels[key]));
first = false;
}
result.Append("}");
return result.ToString();
}
#endif
private void EnterRegionIfNeeded(BoundNode node)
{
if (TrackingRegions && node == this.firstInRegion && this.regionPlace == RegionPlace.Before)
{
EnterRegion();
}
}
/// <summary>
/// Subclasses may override EnterRegion to perform any actions at the entry to the region.
/// </summary>
protected virtual void EnterRegion()
{
Debug.Assert(this.regionPlace == RegionPlace.Before);
this.regionPlace = RegionPlace.Inside;
}
private void LeaveRegionIfNeeded(BoundNode node)
{
if (TrackingRegions && node == this.lastInRegion && this.regionPlace == RegionPlace.Inside)
{
LeaveRegion();
}
}
/// <summary>
/// Subclasses may override LeaveRegion to perform any action at the end of the region.
/// </summary>
protected virtual void LeaveRegion()
{
Debug.Assert(IsInside);
this.regionPlace = RegionPlace.After;
}
protected readonly TextSpan RegionSpan;
protected bool RegionContains(TextSpan span)
{
// TODO: There are no scenarios involving a zero-length span
// currently. If the assert fails, add a corresponding test.
Debug.Assert(span.Length > 0);
if (span.Length == 0)
{
return RegionSpan.Contains(span.Start);
}
return RegionSpan.Contains(span);
}
protected bool IsInside
{
get
{
return regionPlace == RegionPlace.Inside;
}
}
protected virtual void EnterParameters(ImmutableArray<ParameterSymbol> parameters)
{
foreach (var parameter in parameters)
{
EnterParameter(parameter);
}
}
protected virtual void EnterParameter(ParameterSymbol parameter)
{ }
protected virtual void LeaveParameters(
ImmutableArray<ParameterSymbol> parameters,
SyntaxNode syntax,
Location location)
{
foreach (ParameterSymbol parameter in parameters)
{
LeaveParameter(parameter, syntax, location);
}
}
protected virtual void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location)
{ }
public override BoundNode Visit(BoundNode node)
{
return VisitAlways(node);
}
protected BoundNode VisitAlways(BoundNode node)
{
BoundNode result = null;
// We scan even expressions, because we must process lambdas contained within them.
if (node != null)
{
EnterRegionIfNeeded(node);
VisitWithStackGuard(node);
LeaveRegionIfNeeded(node);
}
return result;
}
[DebuggerStepThrough]
private BoundNode VisitWithStackGuard(BoundNode node)
{
var expression = node as BoundExpression;
if (expression != null)
{
return VisitExpressionWithStackGuard(ref _recursionDepth, expression);
}
return base.Visit(node);
}
[DebuggerStepThrough]
protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
{
return (BoundExpression)base.Visit(node);
}
protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()
{
return false; // just let the original exception bubble up.
}
/// <summary>
/// A pending branch. These are created for a return, break, continue, goto statement,
/// yield return, yield break, await expression, and await foreach/using. The idea is that
/// we don't know if the branch will eventually reach its destination because of an
/// intervening finally block that cannot complete normally. So we store them up and handle
/// them as we complete processing each construct. At the end of a block, if there are any
/// pending branches to a label in that block we process the branch. Otherwise we relay it
/// up to the enclosing construct as a pending branch of the enclosing construct.
/// </summary>
internal class PendingBranch
{
public readonly BoundNode Branch;
public bool IsConditionalState;
public TLocalState State;
public TLocalState StateWhenTrue;
public TLocalState StateWhenFalse;
public readonly LabelSymbol Label;
public PendingBranch(BoundNode branch, TLocalState state, LabelSymbol label, bool isConditionalState = false, TLocalState stateWhenTrue = default, TLocalState stateWhenFalse = default)
{
this.Branch = branch;
this.State = state.Clone();
this.IsConditionalState = isConditionalState;
if (isConditionalState)
{
this.StateWhenTrue = stateWhenTrue.Clone();
this.StateWhenFalse = stateWhenFalse.Clone();
}
this.Label = label;
}
}
/// <summary>
/// Perform a single pass of flow analysis. Note that after this pass,
/// this.backwardBranchChanged indicates if a further pass is required.
/// </summary>
protected virtual ImmutableArray<PendingBranch> Scan(ref bool badRegion)
{
var oldPending = SavePending();
Visit(methodMainNode);
this.Unsplit();
RestorePending(oldPending);
if (TrackingRegions && regionPlace != RegionPlace.After)
{
badRegion = true;
}
ImmutableArray<PendingBranch> result = RemoveReturns();
return result;
}
protected ImmutableArray<PendingBranch> Analyze(ref bool badRegion, Optional<TLocalState> initialState = default)
{
ImmutableArray<PendingBranch> returns;
do
{
// the entry point of a method is assumed reachable
regionPlace = RegionPlace.Before;
this.State = initialState.HasValue ? initialState.Value : TopState();
PendingBranches.Clear();
this.stateChangedAfterUse = false;
this.Diagnostics.Clear();
returns = this.Scan(ref badRegion);
}
while (this.stateChangedAfterUse);
return returns;
}
protected virtual void Free()
{
this.Diagnostics.Free();
PendingBranches.Free();
_labelsSeen.Free();
_labels.Free();
}
/// <summary>
/// If a method is currently being analyzed returns its parameters, returns an empty array
/// otherwise.
/// </summary>
protected ImmutableArray<ParameterSymbol> MethodParameters
{
get
{
var method = _symbol as MethodSymbol;
return (object)method == null ? ImmutableArray<ParameterSymbol>.Empty : method.Parameters;
}
}
/// <summary>
/// If a method is currently being analyzed returns its 'this' parameter, returns null
/// otherwise.
/// </summary>
protected ParameterSymbol MethodThisParameter
{
get
{
ParameterSymbol thisParameter = null;
(_symbol as MethodSymbol)?.TryGetThisParameter(out thisParameter);
return thisParameter;
}
}
/// <summary>
/// Specifies whether or not method's out parameters should be analyzed. If there's more
/// than one location in the method being analyzed, then the method is partial and we prefer
/// to report an out parameter in partial method error.
/// </summary>
/// <param name="location">location to be used</param>
/// <returns>true if the out parameters of the method should be analyzed</returns>
protected bool ShouldAnalyzeOutParameters(out Location location)
{
var method = _symbol as MethodSymbol;
if ((object)method == null || method.Locations.Length != 1)
{
location = null;
return false;
}
else
{
location = method.Locations[0];
return true;
}
}
/// <summary>
/// Return the flow analysis state associated with a label.
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
protected virtual TLocalState LabelState(LabelSymbol label)
{
TLocalState result;
if (_labels.TryGetValue(label, out result))
{
return result;
}
result = UnreachableState();
_labels.Add(label, result);
return result;
}
/// <summary>
/// Return to the caller the set of pending return statements.
/// </summary>
/// <returns></returns>
protected virtual ImmutableArray<PendingBranch> RemoveReturns()
{
ImmutableArray<PendingBranch> result;
result = PendingBranches.ToImmutable();
PendingBranches.Clear();
// The caller should have handled and cleared labelsSeen.
Debug.Assert(_labelsSeen.Count == 0);
return result;
}
/// <summary>
/// Set the current state to one that indicates that it is unreachable.
/// </summary>
protected void SetUnreachable()
{
this.State = UnreachableState();
}
protected void VisitLvalue(BoundExpression node)
{
EnterRegionIfNeeded(node);
switch (node?.Kind)
{
case BoundKind.Parameter:
VisitLvalueParameter((BoundParameter)node);
break;
case BoundKind.Local:
VisitLvalue((BoundLocal)node);
break;
case BoundKind.ThisReference:
case BoundKind.BaseReference:
break;
case BoundKind.PropertyAccess:
var access = (BoundPropertyAccess)node;
if (Binder.AccessingAutoPropertyFromConstructor(access, _symbol))
{
var backingField = (access.PropertySymbol as SourcePropertySymbolBase)?.BackingField;
if (backingField != null)
{
VisitFieldAccessInternal(access.ReceiverOpt, backingField);
break;
}
}
goto default;
case BoundKind.FieldAccess:
{
BoundFieldAccess node1 = (BoundFieldAccess)node;
VisitFieldAccessInternal(node1.ReceiverOpt, node1.FieldSymbol);
break;
}
case BoundKind.EventAccess:
{
BoundEventAccess node1 = (BoundEventAccess)node;
VisitFieldAccessInternal(node1.ReceiverOpt, node1.EventSymbol.AssociatedField);
break;
}
case BoundKind.TupleLiteral:
case BoundKind.ConvertedTupleLiteral:
((BoundTupleExpression)node).VisitAllElements((x, self) => self.VisitLvalue(x), this);
break;
default:
VisitRvalue(node);
break;
}
LeaveRegionIfNeeded(node);
}
protected virtual void VisitLvalue(BoundLocal node)
{
}
/// <summary>
/// Visit a boolean condition expression.
/// </summary>
/// <param name="node"></param>
protected void VisitCondition(BoundExpression node)
{
Visit(node);
AdjustConditionalState(node);
}
private void AdjustConditionalState(BoundExpression node)
{
if (IsConstantTrue(node))
{
Unsplit();
SetConditionalState(this.State, UnreachableState());
}
else if (IsConstantFalse(node))
{
Unsplit();
SetConditionalState(UnreachableState(), this.State);
}
else if ((object)node.Type == null || node.Type.SpecialType != SpecialType.System_Boolean)
{
// a dynamic type or a type with operator true/false
Unsplit();
}
Split();
}
/// <summary>
/// Visit a general expression, where we will only need to determine if variables are
/// assigned (or not). That is, we will not be needing AssignedWhenTrue and
/// AssignedWhenFalse.
/// </summary>
/// <param name="isKnownToBeAnLvalue">True when visiting an rvalue that will actually be used as an lvalue,
/// for example a ref parameter when simulating a read of it, or an argument corresponding to an in parameter</param>
protected virtual void VisitRvalue(BoundExpression node, bool isKnownToBeAnLvalue = false)
{
Visit(node);
Unsplit();
}
/// <summary>
/// Visit a statement.
/// </summary>
[DebuggerHidden]
protected virtual void VisitStatement(BoundStatement statement)
{
Visit(statement);
Debug.Assert(!this.IsConditionalState);
}
protected static bool IsConstantTrue(BoundExpression node)
{
return node.ConstantValue == ConstantValue.True;
}
protected static bool IsConstantFalse(BoundExpression node)
{
return node.ConstantValue == ConstantValue.False;
}
protected static bool IsConstantNull(BoundExpression node)
{
return node.ConstantValue == ConstantValue.Null;
}
/// <summary>
/// Called at the point in a loop where the backwards branch would go to.
/// </summary>
private void LoopHead(BoundLoopStatement node)
{
TLocalState previousState;
if (_loopHeadState.TryGetValue(node, out previousState))
{
Join(ref this.State, ref previousState);
}
_loopHeadState[node] = this.State.Clone();
}
/// <summary>
/// Called at the point in a loop where the backward branch is placed.
/// </summary>
private void LoopTail(BoundLoopStatement node)
{
var oldState = _loopHeadState[node];
if (Join(ref oldState, ref this.State))
{
_loopHeadState[node] = oldState;
this.stateChangedAfterUse = true;
}
}
/// <summary>
/// Used to resolve break statements in each statement form that has a break statement
/// (loops, switch).
/// </summary>
private void ResolveBreaks(TLocalState breakState, LabelSymbol label)
{
var pendingBranches = PendingBranches;
var count = pendingBranches.Count;
if (count != 0)
{
int stillPending = 0;
for (int i = 0; i < count; i++)
{
var pending = pendingBranches[i];
if (pending.Label == label)
{
Join(ref breakState, ref pending.State);
}
else
{
if (stillPending != i)
{
pendingBranches[stillPending] = pending;
}
stillPending++;
}
}
pendingBranches.Clip(stillPending);
}
SetState(breakState);
}
/// <summary>
/// Used to resolve continue statements in each statement form that supports it.
/// </summary>
private void ResolveContinues(LabelSymbol continueLabel)
{
var pendingBranches = PendingBranches;
var count = pendingBranches.Count;
if (count != 0)
{
int stillPending = 0;
for (int i = 0; i < count; i++)
{
var pending = pendingBranches[i];
if (pending.Label == continueLabel)
{
// Technically, nothing in the language specification depends on the state
// at the continue label, so we could just discard them instead of merging
// the states. In fact, we need not have added continue statements to the
// pending jump queue in the first place if we were interested solely in the
// flow analysis. However, region analysis (in support of extract method)
// and other forms of more precise analysis
// depend on continue statements appearing in the pending branch queue, so
// we process them from the queue here.
Join(ref this.State, ref pending.State);
}
else
{
if (stillPending != i)
{
pendingBranches[stillPending] = pending;
}
stillPending++;
}
}
pendingBranches.Clip(stillPending);
}
}
/// <summary>
/// Subclasses override this if they want to take special actions on processing a goto
/// statement, when both the jump and the label have been located.
/// </summary>
protected virtual void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement target)
{
target.AssertIsLabeledStatement();
}
/// <summary>
/// To handle a label, we resolve all branches to that label. Returns true if the state of
/// the label changes as a result.
/// </summary>
/// <param name="label">Target label</param>
/// <param name="target">Statement containing the target label</param>
private bool ResolveBranches(LabelSymbol label, BoundStatement target)
{
target?.AssertIsLabeledStatementWithLabel(label);
bool labelStateChanged = false;
var pendingBranches = PendingBranches;
var count = pendingBranches.Count;
if (count != 0)
{
int stillPending = 0;
for (int i = 0; i < count; i++)
{
var pending = pendingBranches[i];
if (pending.Label == label)
{
ResolveBranch(pending, label, target, ref labelStateChanged);
}
else
{
if (stillPending != i)
{
pendingBranches[stillPending] = pending;
}
stillPending++;
}
}
pendingBranches.Clip(stillPending);
}
return labelStateChanged;
}
protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged)
{
var state = LabelState(label);
if (target != null)
{
NoteBranch(pending, pending.Branch, target);
}
var changed = Join(ref state, ref pending.State);
if (changed)
{
labelStateChanged = true;
_labels[label] = state;
}
}
protected struct SavedPending
{
public readonly ArrayBuilder<PendingBranch> PendingBranches;
public readonly PooledHashSet<BoundStatement> LabelsSeen;
public SavedPending(ArrayBuilder<PendingBranch> pendingBranches, PooledHashSet<BoundStatement> labelsSeen)
{
this.PendingBranches = pendingBranches;
this.LabelsSeen = labelsSeen;
}
}
/// <summary>
/// Since branches cannot branch into constructs, only out, we save the pending branches
/// when visiting more nested constructs. When tracking exceptions, we store the current
/// state as the exception state for the following code.
/// </summary>
protected SavedPending SavePending()
{
Debug.Assert(!this.IsConditionalState);
var result = new SavedPending(PendingBranches, _labelsSeen);
PendingBranches = ArrayBuilder<PendingBranch>.GetInstance();
_labelsSeen = PooledHashSet<BoundStatement>.GetInstance();
return result;
}
/// <summary>
/// We use this when closing a block that may contain labels or branches
/// - branches to new labels are resolved
/// - new labels are removed (no longer can be reached)
/// - unresolved pending branches are carried forward
/// </summary>
/// <param name="oldPending">The old pending branches, which are to be merged with the current ones</param>
protected void RestorePending(SavedPending oldPending)
{
foreach (var node in _labelsSeen)
{
switch (node.Kind)
{
case BoundKind.LabeledStatement:
{
var label = (BoundLabeledStatement)node;
stateChangedAfterUse |= ResolveBranches(label.Label, label);
}
break;
case BoundKind.LabelStatement:
{
var label = (BoundLabelStatement)node;
stateChangedAfterUse |= ResolveBranches(label.Label, label);
}
break;
case BoundKind.SwitchSection:
{
var sec = (BoundSwitchSection)node;
foreach (var label in sec.SwitchLabels)
{
stateChangedAfterUse |= ResolveBranches(label.Label, sec);
}
}
break;
default:
// there are no other kinds of labels
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
oldPending.PendingBranches.AddRange(this.PendingBranches);
PendingBranches.Free();
PendingBranches = oldPending.PendingBranches;
// We only use SavePending/RestorePending when there could be no branch into the region between them.
// So there is no need to save the labels seen between the calls. If there were such a need, we would
// do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment
_labelsSeen.Free();
_labelsSeen = oldPending.LabelsSeen;
}
#region visitors
/// <summary>
/// Since each language construct must be handled according to the rules of the language specification,
/// the default visitor reports that the construct for the node is not implemented in the compiler.
/// </summary>
public override BoundNode DefaultVisit(BoundNode node)
{
Debug.Assert(false, $"Should Visit{node.Kind} be overridden in {this.GetType().Name}?");
Diagnostics.Add(ErrorCode.ERR_InternalError, node.Syntax.Location);
return null;
}
public override BoundNode VisitAttribute(BoundAttribute node)
{
// No flow analysis is ever done in attributes (or their arguments).
return null;
}
public override BoundNode VisitThrowExpression(BoundThrowExpression node)
{
VisitRvalue(node.Expression);
SetUnreachable();
return node;
}
public override BoundNode VisitPassByCopy(BoundPassByCopy node)
{
VisitRvalue(node.Expression);
return node;
}
public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node)
{
Debug.Assert(!IsConditionalState);
bool negated = node.Pattern.IsNegated(out var pattern);
Debug.Assert(negated == node.IsNegated);
if (VisitPossibleConditionalAccess(node.Expression, out var stateWhenNotNull))
{
Debug.Assert(!IsConditionalState);
SetConditionalState(patternMatchesNull(pattern)
? (State, stateWhenNotNull)
: (stateWhenNotNull, State));
}
else if (IsConditionalState)
{
// Patterns which only match a single boolean value should propagate conditional state
// for example, `(a != null && a.M(out x)) is true` should have the same conditional state as `(a != null && a.M(out x))`.
if (isBoolTest(pattern) is bool value)
{
if (!value)
{
SetConditionalState(StateWhenFalse, StateWhenTrue);
}
}
else
{
// Patterns which match more than a single boolean value cannot propagate conditional state
// for example, `(a != null && a.M(out x)) is bool b` should not have conditional state
Unsplit();
}
}
VisitPattern(pattern);
var reachableLabels = node.DecisionDag.ReachableLabels;
if (!reachableLabels.Contains(node.WhenTrueLabel))
{
SetState(this.StateWhenFalse);
SetConditionalState(UnreachableState(), this.State);
}
else if (!reachableLabels.Contains(node.WhenFalseLabel))
{
SetState(this.StateWhenTrue);
SetConditionalState(this.State, UnreachableState());
}
if (negated)
{
SetConditionalState(this.StateWhenFalse, this.StateWhenTrue);
}
return node;
static bool patternMatchesNull(BoundPattern pattern)
{
switch (pattern)
{
case BoundTypePattern:
case BoundRecursivePattern:
case BoundITuplePattern:
case BoundRelationalPattern:
case BoundDeclarationPattern { IsVar: false }:
case BoundConstantPattern { ConstantValue: { IsNull: false } }:
return false;
case BoundConstantPattern { ConstantValue: { IsNull: true } }:
return true;
case BoundNegatedPattern negated:
return !patternMatchesNull(negated.Negated);
case BoundBinaryPattern binary:
if (binary.Disjunction)
{
// `a?.b(out x) is null or C`
// pattern matches null if either subpattern matches null
var leftNullTest = patternMatchesNull(binary.Left);
return patternMatchesNull(binary.Left) || patternMatchesNull(binary.Right);
}
// `a?.b out x is not null and var c`
// pattern matches null only if both subpatterns match null
return patternMatchesNull(binary.Left) && patternMatchesNull(binary.Right);
case BoundDeclarationPattern { IsVar: true }:
case BoundDiscardPattern:
return true;
default:
throw ExceptionUtilities.UnexpectedValue(pattern.Kind);
}
}
// Returns `true` if the pattern only matches a `true` input.
// Returns `false` if the pattern only matches a `false` input.
// Otherwise, returns `null`.
static bool? isBoolTest(BoundPattern pattern)
{
switch (pattern)
{
case BoundConstantPattern { ConstantValue: { IsBoolean: true, BooleanValue: var boolValue } }:
return boolValue;
case BoundNegatedPattern negated:
return !isBoolTest(negated.Negated);
case BoundBinaryPattern binary:
if (binary.Disjunction)
{
// `(a != null && a.b(out x)) is true or true` matches `true`
// `(a != null && a.b(out x)) is true or false` matches any boolean
// both subpatterns must have the same bool test for the test to propagate out
var leftNullTest = isBoolTest(binary.Left);
return leftNullTest is null ? null :
leftNullTest != isBoolTest(binary.Right) ? null :
leftNullTest;
}
// `(a != null && a.b(out x)) is true and true` matches `true`
// `(a != null && a.b(out x)) is true and var x` matches `true`
// `(a != null && a.b(out x)) is true and false` never matches and is a compile error
return isBoolTest(binary.Left) ?? isBoolTest(binary.Right);
case BoundConstantPattern { ConstantValue: { IsBoolean: false } }:
case BoundDiscardPattern:
case BoundTypePattern:
case BoundRecursivePattern:
case BoundITuplePattern:
case BoundRelationalPattern:
case BoundDeclarationPattern:
return null;
default:
throw ExceptionUtilities.UnexpectedValue(pattern.Kind);
}
}
}
public virtual void VisitPattern(BoundPattern pattern)
{
Split();
}
public override BoundNode VisitConstantPattern(BoundConstantPattern node)
{
// All patterns are handled by VisitPattern
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitTupleLiteral(BoundTupleLiteral node)
{
return VisitTupleExpression(node);
}
public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node)
{
return VisitTupleExpression(node);
}
private BoundNode VisitTupleExpression(BoundTupleExpression node)
{
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), null);
return null;
}
public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node)
{
VisitRvalue(node.Left);
VisitRvalue(node.Right);
return null;
}
public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node)
{
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node)
{
VisitRvalue(node.Receiver);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
return null;
}
public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node)
{
VisitRvalue(node.Receiver);
return null;
}
public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node)
{
VisitRvalue(node.Expression);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
return null;
}
protected BoundNode VisitInterpolatedStringBase(BoundInterpolatedStringBase node, InterpolatedStringHandlerData? data)
{
// If there can be any branching, then we need to treat the expressions
// as optionally evaluated. Otherwise, we treat them as always evaluated
switch (data)
{
case null:
visitParts();
break;
case { HasTrailingHandlerValidityParameter: false, UsesBoolReturns: false, Construction: var construction }:
VisitRvalue(construction);
visitParts();
break;
case { UsesBoolReturns: var usesBoolReturns, HasTrailingHandlerValidityParameter: var hasTrailingValidityParameter, Construction: var construction }:
VisitRvalue(construction);
if (node.Parts.IsEmpty)
{
break;
}
TLocalState beforePartsState;
ReadOnlySpan<BoundExpression> remainingParts;
if (hasTrailingValidityParameter)
{
beforePartsState = State.Clone();
remainingParts = node.Parts.AsSpan();
}
else
{
Visit(node.Parts[0]);
beforePartsState = State.Clone();
remainingParts = node.Parts.AsSpan()[1..];
}
foreach (var expr in remainingParts)
{
VisitRvalue(expr);
if (usesBoolReturns)
{
Join(ref beforePartsState, ref State);
}
}
if (usesBoolReturns)
{
// Already been joined after the last part, just assign
State = beforePartsState;
}
else
{
Debug.Assert(hasTrailingValidityParameter);
Join(ref State, ref beforePartsState);
}
break;
}
return null;
void visitParts()
{
foreach (var expr in node.Parts)
{
VisitRvalue(expr);
}
}
}
public override BoundNode VisitInterpolatedString(BoundInterpolatedString node)
{
return VisitInterpolatedStringBase(node, node.InterpolationData);
}
public override BoundNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node)
{
// If the node is unconverted, we'll just treat it as if the contents are always evaluated
return VisitInterpolatedStringBase(node, data: null);
}
public override BoundNode VisitStringInsert(BoundStringInsert node)
{
VisitRvalue(node.Value);
if (node.Alignment != null)
{
VisitRvalue(node.Alignment);
}
if (node.Format != null)
{
VisitRvalue(node.Format);
}
return null;
}
public override BoundNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node)
{
return null;
}
public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node)
{
return null;
}
public override BoundNode VisitArgList(BoundArgList node)
{
// The "__arglist" expression that is legal inside a varargs method has no
// effect on flow analysis and it has no children.
return null;
}
public override BoundNode VisitArgListOperator(BoundArgListOperator node)
{
// When we have M(__arglist(x, y, z)) we must visit x, y and z.
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
return null;
}
public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node)
{
// Note that we require that the variable whose reference we are taking
// has been initialized; it is similar to passing the variable as a ref parameter.
VisitRvalue(node.Operand, isKnownToBeAnLvalue: true);
return null;
}
public override BoundNode VisitRefValueOperator(BoundRefValueOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node)
{
VisitStatement(node.Statement);
return null;
}
public override BoundNode VisitLambda(BoundLambda node) => null;
public override BoundNode VisitLocal(BoundLocal node)
{
SplitIfBooleanConstant(node);
return null;
}
public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node)
{
if (node.InitializerOpt != null)
{
// analyze the expression
VisitRvalue(node.InitializerOpt, isKnownToBeAnLvalue: node.LocalSymbol.RefKind != RefKind.None);
// byref assignment is also a potential write
if (node.LocalSymbol.RefKind != RefKind.None)
{
WriteArgument(node.InitializerOpt, node.LocalSymbol.RefKind, method: null);
}
}
return null;
}
public override BoundNode VisitBlock(BoundBlock node)
{
VisitStatements(node.Statements);
return null;
}
private void VisitStatements(ImmutableArray<BoundStatement> statements)
{
foreach (var statement in statements)
{
VisitStatement(statement);
}
}
public override BoundNode VisitScope(BoundScope node)
{
VisitStatements(node.Statements);
return null;
}
public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitCall(BoundCall node)
{
// If the method being called is a partial method without a definition, or is a conditional method
// whose condition is not true, then the call has no effect and it is ignored for the purposes of
// definite assignment analysis.
bool callsAreOmitted = node.Method.CallsAreOmitted(node.SyntaxTree);
TLocalState savedState = default(TLocalState);
if (callsAreOmitted)
{
savedState = this.State.Clone();
SetUnreachable();
}
VisitReceiverBeforeCall(node.ReceiverOpt, node.Method);
VisitArgumentsBeforeCall(node.Arguments, node.ArgumentRefKindsOpt);
if (node.Method?.OriginalDefinition is LocalFunctionSymbol localFunc)
{
VisitLocalFunctionUse(localFunc, node.Syntax, isCall: true);
}
VisitArgumentsAfterCall(node.Arguments, node.ArgumentRefKindsOpt, node.Method);
VisitReceiverAfterCall(node.ReceiverOpt, node.Method);
if (callsAreOmitted)
{
this.State = savedState;
}
return null;
}
protected void VisitLocalFunctionUse(LocalFunctionSymbol symbol, SyntaxNode syntax, bool isCall)
{
var localFuncState = GetOrCreateLocalFuncUsages(symbol);
VisitLocalFunctionUse(symbol, localFuncState, syntax, isCall);
}
protected virtual void VisitLocalFunctionUse(
LocalFunctionSymbol symbol,
TLocalFunctionState localFunctionState,
SyntaxNode syntax,
bool isCall)
{
if (isCall)
{
Join(ref State, ref localFunctionState.StateFromBottom);
Meet(ref State, ref localFunctionState.StateFromTop);
}
localFunctionState.Visited = true;
}
private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method)
{
if (method is null || method.MethodKind != MethodKind.Constructor)
{
VisitRvalue(receiverOpt);
}
}
private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method)
{
if (receiverOpt is null)
{
return;
}
if (method is null)
{
WriteArgument(receiverOpt, RefKind.Ref, method: null);
}
else if (method.TryGetThisParameter(out var thisParameter)
&& thisParameter is object
&& !TypeIsImmutable(thisParameter.Type))
{
var thisRefKind = thisParameter.RefKind;
if (thisRefKind.IsWritableReference())
{
WriteArgument(receiverOpt, thisRefKind, method);
}
}
}
/// <summary>
/// Certain (struct) types are known by the compiler to be immutable. In these cases calling a method on
/// the type is known (by flow analysis) not to write the receiver.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private static bool TypeIsImmutable(TypeSymbol t)
{
switch (t.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_DateTime:
return true;
default:
return t.IsNullableType();
}
}
public override BoundNode VisitIndexerAccess(BoundIndexerAccess node)
{
var method = GetReadMethod(node.Indexer);
VisitReceiverBeforeCall(node.ReceiverOpt, method);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method);
if ((object)method != null)
{
VisitReceiverAfterCall(node.ReceiverOpt, method);
}
return null;
}
public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node)
{
// Index or Range pattern indexers evaluate the following in order:
// 1. The receiver
// 1. The Count or Length method off the receiver
// 2. The argument to the access
// 3. The pattern method
VisitRvalue(node.Receiver);
var method = GetReadMethod(node.LengthOrCountProperty);
VisitReceiverAfterCall(node.Receiver, method);
VisitRvalue(node.Argument);
method = node.PatternSymbol switch
{
PropertySymbol p => GetReadMethod(p),
MethodSymbol m => m,
_ => throw ExceptionUtilities.UnexpectedValue(node.PatternSymbol)
};
VisitReceiverAfterCall(node.Receiver, method);
return null;
}
public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node)
{
VisitRvalue(node.ReceiverOpt);
VisitRvalue(node.Argument);
return null;
}
/// <summary>
/// Do not call for a local function.
/// </summary>
protected virtual void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method)
{
Debug.Assert(method?.OriginalDefinition.MethodKind != MethodKind.LocalFunction);
VisitArgumentsBeforeCall(arguments, refKindsOpt);
VisitArgumentsAfterCall(arguments, refKindsOpt, method);
}
private void VisitArgumentsBeforeCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt)
{
// first value and ref parameters are read...
for (int i = 0; i < arguments.Length; i++)
{
RefKind refKind = GetRefKind(refKindsOpt, i);
if (refKind != RefKind.Out)
{
VisitRvalue(arguments[i], isKnownToBeAnLvalue: refKind != RefKind.None);
}
else
{
VisitLvalue(arguments[i]);
}
}
}
/// <summary>
/// Writes ref and out parameters
/// </summary>
private void VisitArgumentsAfterCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method)
{
for (int i = 0; i < arguments.Length; i++)
{
RefKind refKind = GetRefKind(refKindsOpt, i);
// passing as a byref argument is also a potential write
if (refKind != RefKind.None)
{
WriteArgument(arguments[i], refKind, method);
}
}
}
protected static RefKind GetRefKind(ImmutableArray<RefKind> refKindsOpt, int index)
{
return refKindsOpt.IsDefault || refKindsOpt.Length <= index ? RefKind.None : refKindsOpt[index];
}
protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method)
{
}
public override BoundNode VisitBadExpression(BoundBadExpression node)
{
foreach (var child in node.ChildBoundNodes)
{
VisitRvalue(child as BoundExpression);
}
return null;
}
public override BoundNode VisitBadStatement(BoundBadStatement node)
{
foreach (var child in node.ChildBoundNodes)
{
if (child is BoundStatement)
{
VisitStatement(child as BoundStatement);
}
else
{
VisitRvalue(child as BoundExpression);
}
}
return null;
}
// Can be called as part of a bad expression.
public override BoundNode VisitArrayInitialization(BoundArrayInitialization node)
{
foreach (var child in node.Initializers)
{
VisitRvalue(child);
}
return null;
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
var methodGroup = node.Argument as BoundMethodGroup;
if (methodGroup != null)
{
if ((object)node.MethodOpt != null && node.MethodOpt.RequiresInstanceReceiver)
{
EnterRegionIfNeeded(methodGroup);
VisitRvalue(methodGroup.ReceiverOpt);
LeaveRegionIfNeeded(methodGroup);
}
else if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc)
{
VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false);
}
}
else
{
VisitRvalue(node.Argument);
}
return null;
}
public override BoundNode VisitTypeExpression(BoundTypeExpression node)
{
return null;
}
public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node)
{
// If we're seeing a node of this kind, then we failed to resolve the member access
// as either a type or a property/field/event/local/parameter. In such cases,
// the second interpretation applies so just visit the node for that.
return this.Visit(node.Data.ValueExpression);
}
public override BoundNode VisitLiteral(BoundLiteral node)
{
SplitIfBooleanConstant(node);
return null;
}
protected void SplitIfBooleanConstant(BoundExpression node)
{
if (node.ConstantValue is { IsBoolean: true, BooleanValue: bool booleanValue })
{
var unreachable = UnreachableState();
Split();
if (booleanValue)
{
StateWhenFalse = unreachable;
}
else
{
StateWhenTrue = unreachable;
}
}
}
public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node)
{
return null;
}
public override BoundNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node)
{
return null;
}
public override BoundNode VisitModuleVersionId(BoundModuleVersionId node)
{
return null;
}
public override BoundNode VisitModuleVersionIdString(BoundModuleVersionIdString node)
{
return null;
}
public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node)
{
return null;
}
public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node)
{
return null;
}
public override BoundNode VisitConversion(BoundConversion node)
{
if (node.ConversionKind == ConversionKind.MethodGroup)
{
if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && node.SymbolOpt.RequiresInstanceReceiver))
{
BoundExpression receiver = ((BoundMethodGroup)node.Operand).ReceiverOpt;
// A method group's "implicit this" is only used for instance methods.
EnterRegionIfNeeded(node.Operand);
VisitRvalue(receiver);
LeaveRegionIfNeeded(node.Operand);
}
else if (node.SymbolOpt?.OriginalDefinition is LocalFunctionSymbol localFunc)
{
VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false);
}
}
else
{
Visit(node.Operand);
}
return null;
}
public override BoundNode VisitIfStatement(BoundIfStatement node)
{
// 5.3.3.5 If statements
VisitCondition(node.Condition);
TLocalState trueState = StateWhenTrue;
TLocalState falseState = StateWhenFalse;
SetState(trueState);
VisitStatement(node.Consequence);
trueState = this.State;
SetState(falseState);
if (node.AlternativeOpt != null)
{
VisitStatement(node.AlternativeOpt);
}
Join(ref this.State, ref trueState);
return null;
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var oldPending = SavePending(); // we do not allow branches into a try statement
var initialState = this.State.Clone();
// use this state to resolve all the branches introduced and internal to try/catch
var pendingBeforeTry = SavePending();
VisitTryBlockWithAnyTransferFunction(node.TryBlock, node, ref initialState);
var finallyState = initialState.Clone();
var endState = this.State;
foreach (var catchBlock in node.CatchBlocks)
{
SetState(initialState.Clone());
VisitCatchBlockWithAnyTransferFunction(catchBlock, ref finallyState);
Join(ref endState, ref this.State);
}
// Give a chance to branches internal to try/catch to resolve.
// Carry forward unresolved branches.
RestorePending(pendingBeforeTry);
// NOTE: At this point all branches that are internal to try or catch blocks have been resolved.
// However we have not yet restored the oldPending branches. Therefore all the branches
// that are currently pending must have been introduced in try/catch and do not terminate inside those blocks.
//
// With exception of YieldReturn, these branches logically go through finally, if such present,
// so we must Union/Intersect finally state as appropriate
if (node.FinallyBlockOpt != null)
{
// branches from the finally block, while illegal, should still not be considered
// to execute the finally block before occurring. Also, we do not handle branches
// *into* the finally block.
SetState(finallyState);
// capture tryAndCatchPending before going into finally
// we will need pending branches as they were before finally later
var tryAndCatchPending = SavePending();
var stateMovedUpInFinally = ReachableBottomState();
VisitFinallyBlockWithAnyTransferFunction(node.FinallyBlockOpt, ref stateMovedUpInFinally);
foreach (var pend in tryAndCatchPending.PendingBranches)
{
if (pend.Branch == null)
{
continue; // a tracked exception
}
if (pend.Branch.Kind != BoundKind.YieldReturnStatement)
{
updatePendingBranchState(ref pend.State, ref stateMovedUpInFinally);
if (pend.IsConditionalState)
{
updatePendingBranchState(ref pend.StateWhenTrue, ref stateMovedUpInFinally);
updatePendingBranchState(ref pend.StateWhenFalse, ref stateMovedUpInFinally);
}
}
}
RestorePending(tryAndCatchPending);
Meet(ref endState, ref this.State);
if (_nonMonotonicTransfer)
{
Join(ref endState, ref stateMovedUpInFinally);
}
}
SetState(endState);
RestorePending(oldPending);
return null;
void updatePendingBranchState(ref TLocalState stateToUpdate, ref TLocalState stateMovedUpInFinally)
{
Meet(ref stateToUpdate, ref this.State);
if (_nonMonotonicTransfer)
{
Join(ref stateToUpdate, ref stateMovedUpInFinally);
}
}
}
protected Optional<TLocalState> NonMonotonicState;
/// <summary>
/// Join state from other try block, potentially in a nested method.
/// </summary>
protected virtual void JoinTryBlockState(ref TLocalState self, ref TLocalState other)
{
Join(ref self, ref other);
}
private void VisitTryBlockWithAnyTransferFunction(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState)
{
if (_nonMonotonicTransfer)
{
Optional<TLocalState> oldTryState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitTryBlock(tryBlock, node, ref tryState);
var tempTryStateValue = NonMonotonicState.Value;
Join(ref tryState, ref tempTryStateValue);
if (oldTryState.HasValue)
{
var oldTryStateValue = oldTryState.Value;
JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue);
oldTryState = oldTryStateValue;
}
NonMonotonicState = oldTryState;
}
else
{
VisitTryBlock(tryBlock, node, ref tryState);
}
}
protected virtual void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState)
{
VisitStatement(tryBlock);
}
private void VisitCatchBlockWithAnyTransferFunction(BoundCatchBlock catchBlock, ref TLocalState finallyState)
{
if (_nonMonotonicTransfer)
{
Optional<TLocalState> oldTryState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitCatchBlock(catchBlock, ref finallyState);
var tempTryStateValue = NonMonotonicState.Value;
Join(ref finallyState, ref tempTryStateValue);
if (oldTryState.HasValue)
{
var oldTryStateValue = oldTryState.Value;
JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue);
oldTryState = oldTryStateValue;
}
NonMonotonicState = oldTryState;
}
else
{
VisitCatchBlock(catchBlock, ref finallyState);
}
}
protected virtual void VisitCatchBlock(BoundCatchBlock catchBlock, ref TLocalState finallyState)
{
if (catchBlock.ExceptionSourceOpt != null)
{
VisitLvalue(catchBlock.ExceptionSourceOpt);
}
if (catchBlock.ExceptionFilterPrologueOpt is { })
{
VisitStatementList(catchBlock.ExceptionFilterPrologueOpt);
}
if (catchBlock.ExceptionFilterOpt != null)
{
VisitCondition(catchBlock.ExceptionFilterOpt);
SetState(StateWhenTrue);
}
VisitStatement(catchBlock.Body);
}
private void VisitFinallyBlockWithAnyTransferFunction(BoundStatement finallyBlock, ref TLocalState stateMovedUp)
{
if (_nonMonotonicTransfer)
{
Optional<TLocalState> oldTryState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitFinallyBlock(finallyBlock, ref stateMovedUp);
var tempTryStateValue = NonMonotonicState.Value;
Join(ref stateMovedUp, ref tempTryStateValue);
if (oldTryState.HasValue)
{
var oldTryStateValue = oldTryState.Value;
JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue);
oldTryState = oldTryStateValue;
}
NonMonotonicState = oldTryState;
}
else
{
VisitFinallyBlock(finallyBlock, ref stateMovedUp);
}
}
protected virtual void VisitFinallyBlock(BoundStatement finallyBlock, ref TLocalState stateMovedUp)
{
VisitStatement(finallyBlock); // this should generate no pending branches
}
public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node)
{
return VisitBlock(node.FinallyBlock);
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
var result = VisitReturnStatementNoAdjust(node);
PendingBranches.Add(new PendingBranch(node, this.State, label: null));
SetUnreachable();
return result;
}
protected virtual BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node)
{
VisitRvalue(node.ExpressionOpt, isKnownToBeAnLvalue: node.RefKind != RefKind.None);
// byref return is also a potential write
if (node.RefKind != RefKind.None)
{
WriteArgument(node.ExpressionOpt, node.RefKind, method: null);
}
return null;
}
public override BoundNode VisitThisReference(BoundThisReference node)
{
return null;
}
public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node)
{
return null;
}
public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node)
{
return null;
}
public override BoundNode VisitParameter(BoundParameter node)
{
return null;
}
protected virtual void VisitLvalueParameter(BoundParameter node)
{
}
public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node)
{
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor);
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
public override BoundNode VisitNewT(BoundNewT node)
{
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node)
{
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
// represents anything that occurs at the invocation of the property setter
protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null)
{
VisitReceiverAfterCall(receiver, setter);
}
// returns false if expression is not a property access
// or if the property has a backing field
// and accessed in a corresponding constructor
private bool RegularPropertyAccess(BoundExpression expr)
{
if (expr.Kind != BoundKind.PropertyAccess)
{
return false;
}
return !Binder.AccessingAutoPropertyFromConstructor((BoundPropertyAccess)expr, _symbol);
}
public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node)
{
// TODO: should events be handled specially too?
if (RegularPropertyAccess(node.Left))
{
var left = (BoundPropertyAccess)node.Left;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var method = GetWriteMethod(property);
VisitReceiverBeforeCall(left.ReceiverOpt, method);
VisitRvalue(node.Right);
PropertySetter(node, left.ReceiverOpt, method, node.Right);
return null;
}
}
VisitLvalue(node.Left);
VisitRvalue(node.Right, isKnownToBeAnLvalue: node.IsRef);
// byref assignment is also a potential write
if (node.IsRef)
{
// Assume that BadExpression is a ref location to avoid
// cascading diagnostics
var refKind = node.Left.Kind == BoundKind.BadExpression
? RefKind.Ref
: node.Left.GetRefKind();
WriteArgument(node.Right, refKind, method: null);
}
return null;
}
public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node)
{
VisitLvalue(node.Left);
VisitRvalue(node.Right);
return null;
}
public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node)
{
// OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
VisitCompoundAssignmentTarget(node);
VisitRvalue(node.Right);
AfterRightHasBeenVisited(node);
return null;
}
protected void VisitCompoundAssignmentTarget(BoundCompoundAssignmentOperator node)
{
// TODO: should events be handled specially too?
if (RegularPropertyAccess(node.Left))
{
var left = (BoundPropertyAccess)node.Left;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var readMethod = GetReadMethod(property);
Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)GetWriteMethod(property));
VisitReceiverBeforeCall(left.ReceiverOpt, readMethod);
VisitReceiverAfterCall(left.ReceiverOpt, readMethod);
return;
}
}
VisitRvalue(node.Left, isKnownToBeAnLvalue: true);
}
protected void AfterRightHasBeenVisited(BoundCompoundAssignmentOperator node)
{
if (RegularPropertyAccess(node.Left))
{
var left = (BoundPropertyAccess)node.Left;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var writeMethod = GetWriteMethod(property);
PropertySetter(node, left.ReceiverOpt, writeMethod);
VisitReceiverAfterCall(left.ReceiverOpt, writeMethod);
return;
}
}
}
public override BoundNode VisitFieldAccess(BoundFieldAccess node)
{
VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol);
SplitIfBooleanConstant(node);
return null;
}
private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol)
{
bool asLvalue = (object)fieldSymbol != null &&
(fieldSymbol.IsFixedSizeBuffer ||
!fieldSymbol.IsStatic &&
fieldSymbol.ContainingType.TypeKind == TypeKind.Struct &&
receiverOpt != null &&
receiverOpt.Kind != BoundKind.TypeExpression &&
(object)receiverOpt.Type != null &&
!receiverOpt.Type.IsPrimitiveRecursiveStruct());
if (asLvalue)
{
VisitLvalue(receiverOpt);
}
else
{
VisitRvalue(receiverOpt);
}
}
public override BoundNode VisitFieldInfo(BoundFieldInfo node)
{
return null;
}
public override BoundNode VisitMethodInfo(BoundMethodInfo node)
{
return null;
}
public override BoundNode VisitPropertyAccess(BoundPropertyAccess node)
{
var property = node.PropertySymbol;
if (Binder.AccessingAutoPropertyFromConstructor(node, _symbol))
{
var backingField = (property as SourcePropertySymbolBase)?.BackingField;
if (backingField != null)
{
VisitFieldAccessInternal(node.ReceiverOpt, backingField);
return null;
}
}
var method = GetReadMethod(property);
VisitReceiverBeforeCall(node.ReceiverOpt, method);
VisitReceiverAfterCall(node.ReceiverOpt, method);
return null;
// TODO: In an expression such as
// M().Prop = G();
// Exceptions thrown from M() occur before those from G(), but exceptions from the property accessor
// occur after both. The precise abstract flow pass does not yet currently have this quite right.
// Probably what is needed is a VisitPropertyAccessInternal(BoundPropertyAccess node, bool read)
// which should assume that the receiver will have been handled by the caller. This can be invoked
// twice for read/write operations such as
// M().Prop += 1
// or at the appropriate place in the sequence for read or write operations.
// Do events require any special handling too?
}
public override BoundNode VisitEventAccess(BoundEventAccess node)
{
VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField);
return null;
}
public override BoundNode VisitRangeVariable(BoundRangeVariable node)
{
return null;
}
public override BoundNode VisitQueryClause(BoundQueryClause node)
{
VisitRvalue(node.UnoptimizedForm ?? node.Value);
return null;
}
private BoundNode VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node)
{
foreach (var v in node.LocalDeclarations)
{
Visit(v);
}
return null;
}
public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node)
{
return VisitMultipleLocalDeclarationsBase(node);
}
public override BoundNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node)
{
if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null)
{
PendingBranches.Add(new PendingBranch(node, this.State, null));
}
return VisitMultipleLocalDeclarationsBase(node);
}
public override BoundNode VisitWhileStatement(BoundWhileStatement node)
{
// while (node.Condition) { node.Body; node.ContinueLabel: } node.BreakLabel:
LoopHead(node);
VisitCondition(node.Condition);
TLocalState bodyState = StateWhenTrue;
TLocalState breakState = StateWhenFalse;
SetState(bodyState);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
return null;
}
public override BoundNode VisitWithExpression(BoundWithExpression node)
{
VisitRvalue(node.Receiver);
VisitObjectOrCollectionInitializerExpression(node.InitializerExpression.Initializers);
return null;
}
public override BoundNode VisitArrayAccess(BoundArrayAccess node)
{
VisitRvalue(node.Expression);
foreach (var i in node.Indices)
{
VisitRvalue(i);
}
return null;
}
public override BoundNode VisitBinaryOperator(BoundBinaryOperator node)
{
if (node.OperatorKind.IsLogical())
{
Debug.Assert(!node.OperatorKind.IsUserDefined());
VisitBinaryLogicalOperatorChildren(node);
}
else
{
VisitBinaryOperatorChildren(node);
}
return null;
}
public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node)
{
VisitBinaryLogicalOperatorChildren(node);
return null;
}
private void VisitBinaryLogicalOperatorChildren(BoundExpression node)
{
// Do not blow the stack due to a deep recursion on the left.
var stack = ArrayBuilder<BoundExpression>.GetInstance();
BoundExpression binary;
BoundExpression child = node;
while (true)
{
var childKind = child.Kind;
if (childKind == BoundKind.BinaryOperator)
{
var binOp = (BoundBinaryOperator)child;
if (!binOp.OperatorKind.IsLogical())
{
break;
}
Debug.Assert(!binOp.OperatorKind.IsUserDefined());
binary = child;
child = binOp.Left;
}
else if (childKind == BoundKind.UserDefinedConditionalLogicalOperator)
{
binary = child;
child = ((BoundUserDefinedConditionalLogicalOperator)binary).Left;
}
else
{
break;
}
stack.Push(binary);
}
Debug.Assert(stack.Count > 0);
VisitCondition(child);
while (true)
{
binary = stack.Pop();
BinaryOperatorKind kind;
BoundExpression right;
switch (binary.Kind)
{
case BoundKind.BinaryOperator:
var binOp = (BoundBinaryOperator)binary;
kind = binOp.OperatorKind;
right = binOp.Right;
break;
case BoundKind.UserDefinedConditionalLogicalOperator:
var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary;
kind = udBinOp.OperatorKind;
right = udBinOp.Right;
break;
default:
throw ExceptionUtilities.UnexpectedValue(binary.Kind);
}
var op = kind.Operator();
var isAnd = op == BinaryOperatorKind.And;
var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool;
Debug.Assert(isAnd || op == BinaryOperatorKind.Or);
var leftTrue = this.StateWhenTrue;
var leftFalse = this.StateWhenFalse;
SetState(isAnd ? leftTrue : leftFalse);
AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse);
if (stack.Count == 0)
{
break;
}
AdjustConditionalState(binary);
}
Debug.Assert((object)binary == node);
stack.Free();
}
protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse)
{
Visit(right); // First part of VisitCondition
AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse);
}
protected void AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse)
{
AdjustConditionalState(right); // Second part of VisitCondition
if (!isBool)
{
this.Unsplit();
this.Split();
}
var resultTrue = this.StateWhenTrue;
var resultFalse = this.StateWhenFalse;
if (isAnd)
{
Join(ref resultFalse, ref leftFalse);
}
else
{
Join(ref resultTrue, ref leftTrue);
}
SetConditionalState(resultTrue, resultFalse);
if (!isBool)
{
this.Unsplit();
}
}
private void VisitBinaryOperatorChildren(BoundBinaryOperator node)
{
// It is common in machine-generated code for there to be deep recursion on the left side of a binary
// operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left
// hand side. To mitigate the risk of stack overflow we use an explicit stack.
//
// Of course we must ensure that we visit the left hand side before the right hand side.
var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance();
BoundBinaryOperator binary = node;
do
{
stack.Push(binary);
binary = binary.Left as BoundBinaryOperator;
}
while (binary != null && !binary.OperatorKind.IsLogical());
VisitBinaryOperatorChildren(stack);
stack.Free();
}
#nullable enable
protected virtual void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack)
{
var binary = stack.Pop();
// Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left
// For simplicity, we just special case it here.
// For example, `a?.b(out x) == true` has a conditional access on the left of the operator,
// but `expr == a?.b(out x) == true` has a conditional access on the right of the operator
if (VisitPossibleConditionalAccess(binary.Left, out var stateWhenNotNull)
&& canLearnFromOperator(binary)
&& isKnownNullOrNotNull(binary.Right))
{
if (_nonMonotonicTransfer)
{
// In this very specific scenario, we need to do extra work to track unassignments for region analysis.
// See `AbstractFlowPass.VisitCatchBlockWithAnyTransferFunction` for a similar scenario in catch blocks.
Optional<TLocalState> oldState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitRvalue(binary.Right);
var tempStateValue = NonMonotonicState.Value;
Join(ref stateWhenNotNull, ref tempStateValue);
if (oldState.HasValue)
{
var oldStateValue = oldState.Value;
Join(ref oldStateValue, ref tempStateValue);
oldState = oldStateValue;
}
NonMonotonicState = oldState;
}
else
{
VisitRvalue(binary.Right);
Meet(ref stateWhenNotNull, ref State);
}
var isNullConstant = binary.Right.ConstantValue?.IsNull == true;
SetConditionalState(isNullConstant == isEquals(binary)
? (State, stateWhenNotNull)
: (stateWhenNotNull, State));
if (stack.Count == 0)
{
return;
}
binary = stack.Pop();
}
while (true)
{
if (!canLearnFromOperator(binary)
|| !learnFromOperator(binary))
{
Unsplit();
Visit(binary.Right);
}
if (stack.Count == 0)
{
break;
}
binary = stack.Pop();
}
static bool canLearnFromOperator(BoundBinaryOperator binary)
{
var kind = binary.OperatorKind;
return kind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual
&& (!kind.IsUserDefined() || kind.IsLifted());
}
static bool isKnownNullOrNotNull(BoundExpression expr)
{
return expr.ConstantValue is object
|| (expr is BoundConversion { ConversionKind: ConversionKind.ExplicitNullable or ConversionKind.ImplicitNullable } conv
&& conv.Operand.Type!.IsNonNullableValueType());
}
static bool isEquals(BoundBinaryOperator binary)
=> binary.OperatorKind.Operator() == BinaryOperatorKind.Equal;
// Returns true if `binary.Right` was visited by the call.
bool learnFromOperator(BoundBinaryOperator binary)
{
// `true == a?.b(out x)`
if (isKnownNullOrNotNull(binary.Left) && TryVisitConditionalAccess(binary.Right, out var stateWhenNotNull))
{
var isNullConstant = binary.Left.ConstantValue?.IsNull == true;
SetConditionalState(isNullConstant == isEquals(binary)
? (State, stateWhenNotNull)
: (stateWhenNotNull, State));
return true;
}
// `a && b(out x) == true`
else if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant)
{
var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone());
Unsplit();
Visit(binary.Right);
SetConditionalState(isEquals(binary) == rightConstant.BooleanValue
? (stateWhenTrue, stateWhenFalse)
: (stateWhenFalse, stateWhenTrue));
return true;
}
// `true == a && b(out x)`
else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant)
{
Unsplit();
Visit(binary.Right);
if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue)
{
SetConditionalState(StateWhenFalse, StateWhenTrue);
}
return true;
}
return false;
}
}
#nullable disable
public override BoundNode VisitUnaryOperator(BoundUnaryOperator node)
{
if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation)
{
// We have a special case for the ! unary operator, which can operate in a boolean context (5.3.3.26)
VisitCondition(node.Operand);
// it inverts the sense of assignedWhenTrue and assignedWhenFalse.
SetConditionalState(StateWhenFalse, StateWhenTrue);
}
else
{
VisitRvalue(node.Operand);
}
return null;
}
public override BoundNode VisitRangeExpression(BoundRangeExpression node)
{
if (node.LeftOperandOpt != null)
{
VisitRvalue(node.LeftOperandOpt);
}
if (node.RightOperandOpt != null)
{
VisitRvalue(node.RightOperandOpt);
}
return null;
}
public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
VisitRvalue(node.Expression);
PendingBranches.Add(new PendingBranch(node, this.State, null));
return null;
}
public override BoundNode VisitIncrementOperator(BoundIncrementOperator node)
{
// TODO: should we also specially handle events?
if (RegularPropertyAccess(node.Operand))
{
var left = (BoundPropertyAccess)node.Operand;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var readMethod = GetReadMethod(property);
var writeMethod = GetWriteMethod(property);
Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod);
VisitReceiverBeforeCall(left.ReceiverOpt, readMethod);
VisitReceiverAfterCall(left.ReceiverOpt, readMethod);
PropertySetter(node, left.ReceiverOpt, writeMethod); // followed by a write
return null;
}
}
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitArrayCreation(BoundArrayCreation node)
{
foreach (var expr in node.Bounds)
{
VisitRvalue(expr);
}
if (node.InitializerOpt != null)
{
VisitArrayInitializationInternal(node, node.InitializerOpt);
}
return null;
}
private void VisitArrayInitializationInternal(BoundArrayCreation arrayCreation, BoundArrayInitialization node)
{
foreach (var child in node.Initializers)
{
if (child.Kind == BoundKind.ArrayInitialization)
{
VisitArrayInitializationInternal(arrayCreation, (BoundArrayInitialization)child);
}
else
{
VisitRvalue(child);
}
}
}
public override BoundNode VisitForStatement(BoundForStatement node)
{
if (node.Initializer != null)
{
VisitStatement(node.Initializer);
}
LoopHead(node);
TLocalState bodyState, breakState;
if (node.Condition != null)
{
VisitCondition(node.Condition);
bodyState = this.StateWhenTrue;
breakState = this.StateWhenFalse;
}
else
{
bodyState = this.State;
breakState = UnreachableState();
}
SetState(bodyState);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
if (node.Increment != null)
{
VisitStatement(node.Increment);
}
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
return null;
}
public override BoundNode VisitForEachStatement(BoundForEachStatement node)
{
// foreach [await] ( var v in node.Expression ) { node.Body; node.ContinueLabel: } node.BreakLabel:
VisitForEachExpression(node);
var breakState = this.State.Clone();
LoopHead(node);
VisitForEachIterationVariables(node);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
if (AwaitUsingAndForeachAddsPendingBranch && ((CommonForEachStatementSyntax)node.Syntax).AwaitKeyword != default)
{
PendingBranches.Add(new PendingBranch(node, this.State, null));
}
return null;
}
protected virtual void VisitForEachExpression(BoundForEachStatement node)
{
VisitRvalue(node.Expression);
}
public virtual void VisitForEachIterationVariables(BoundForEachStatement node)
{
}
public override BoundNode VisitAsOperator(BoundAsOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitIsOperator(BoundIsOperator node)
{
if (VisitPossibleConditionalAccess(node.Operand, out var stateWhenNotNull))
{
Debug.Assert(!IsConditionalState);
SetConditionalState(stateWhenNotNull, State);
}
else
{
// `(a && b.M(out x)) is bool` should discard conditional state from LHS
Unsplit();
}
return null;
}
public override BoundNode VisitMethodGroup(BoundMethodGroup node)
{
if (node.ReceiverOpt != null)
{
// An explicit or implicit receiver, for example in an expression such as (x.Goo is Action, or Goo is Action), is considered to be read.
VisitRvalue(node.ReceiverOpt);
}
return null;
}
#nullable enable
public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node)
{
if (IsConstantNull(node.LeftOperand))
{
VisitRvalue(node.LeftOperand);
Visit(node.RightOperand);
}
else
{
TLocalState savedState;
if (VisitPossibleConditionalAccess(node.LeftOperand, out var stateWhenNotNull))
{
Debug.Assert(!IsConditionalState);
savedState = stateWhenNotNull;
}
else
{
Unsplit();
savedState = State.Clone();
}
if (node.LeftOperand.ConstantValue != null)
{
SetUnreachable();
}
Visit(node.RightOperand);
if (IsConditionalState)
{
Join(ref StateWhenTrue, ref savedState);
Join(ref StateWhenFalse, ref savedState);
}
else
{
Join(ref this.State, ref savedState);
}
}
return null;
}
/// <summary>
/// Visits a node only if it is a conditional access.
/// Returns 'true' if and only if the node was visited.
/// </summary>
private bool TryVisitConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull)
{
var access = node switch
{
BoundConditionalAccess ca => ca,
BoundConversion { Conversion: Conversion conversion, Operand: BoundConditionalAccess ca } when CanPropagateStateWhenNotNull(conversion) => ca,
_ => null
};
if (access is not null)
{
EnterRegionIfNeeded(access);
Unsplit();
VisitConditionalAccess(access, out stateWhenNotNull);
Debug.Assert(!IsConditionalState);
LeaveRegionIfNeeded(access);
return true;
}
stateWhenNotNull = default;
return false;
}
/// <summary>
/// "State when not null" can only propagate out of a conditional access if
/// it is not subject to a user-defined conversion whose parameter is not of a non-nullable value type.
/// </summary>
protected static bool CanPropagateStateWhenNotNull(Conversion conversion)
{
if (!conversion.IsValid)
{
return false;
}
if (!conversion.IsUserDefined)
{
return true;
}
var method = conversion.Method;
Debug.Assert(method is object);
Debug.Assert(method.ParameterCount is 1);
var param = method.Parameters[0];
return param.Type.IsNonNullableValueType();
}
/// <summary>
/// Unconditionally visits an expression.
/// If the expression has "state when not null" after visiting,
/// the method returns 'true' and writes the state to <paramref name="stateWhenNotNull" />.
/// </summary>
private bool VisitPossibleConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull)
{
if (TryVisitConditionalAccess(node, out stateWhenNotNull))
{
return true;
}
else
{
Visit(node);
return false;
}
}
private void VisitConditionalAccess(BoundConditionalAccess node, out TLocalState stateWhenNotNull)
{
// The receiver may also be a conditional access.
// `(a?.b(x = 1))?.c(y = 1)`
if (VisitPossibleConditionalAccess(node.Receiver, out var receiverStateWhenNotNull))
{
stateWhenNotNull = receiverStateWhenNotNull;
}
else
{
Unsplit();
stateWhenNotNull = this.State.Clone();
}
if (node.Receiver.ConstantValue != null && !IsConstantNull(node.Receiver))
{
// Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`.
// We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`.
// Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State
// and includes the "after subsequent conditional accesses" in stateWhenNotNull
if (VisitPossibleConditionalAccess(node.AccessExpression, out var firstAccessStateWhenNotNull))
{
stateWhenNotNull = firstAccessStateWhenNotNull;
}
else
{
Unsplit();
stateWhenNotNull = this.State.Clone();
}
}
else
{
var savedState = this.State.Clone();
if (IsConstantNull(node.Receiver))
{
SetUnreachable();
}
else
{
SetState(stateWhenNotNull);
}
// We want to preserve stateWhenNotNull from accesses in the same "chain":
// a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y)
// but not accesses in nested expressions:
// a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y)
BoundExpression expr = node.AccessExpression;
while (expr is BoundConditionalAccess innerCondAccess)
{
Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion));
// we assume that non-conditional accesses can never contain conditional accesses from the same "chain".
// that is, we never have to dig through non-conditional accesses to find and handle conditional accesses.
VisitRvalue(innerCondAccess.Receiver);
expr = innerCondAccess.AccessExpression;
// The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated.
// e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull.
Join(ref savedState, ref State);
}
Debug.Assert(expr is BoundExpression);
VisitRvalue(expr);
stateWhenNotNull = State;
State = savedState;
Join(ref State, ref stateWhenNotNull);
}
}
public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node)
{
VisitConditionalAccess(node, stateWhenNotNull: out _);
return null;
}
#nullable disable
public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node)
{
VisitRvalue(node.Receiver);
var savedState = this.State.Clone();
VisitRvalue(node.WhenNotNull);
Join(ref this.State, ref savedState);
if (node.WhenNullOpt != null)
{
savedState = this.State.Clone();
VisitRvalue(node.WhenNullOpt);
Join(ref this.State, ref savedState);
}
return null;
}
public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node)
{
return null;
}
public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node)
{
var savedState = this.State.Clone();
VisitRvalue(node.ValueTypeReceiver);
Join(ref this.State, ref savedState);
savedState = this.State.Clone();
VisitRvalue(node.ReferenceTypeReceiver);
Join(ref this.State, ref savedState);
return null;
}
public override BoundNode VisitSequence(BoundSequence node)
{
var sideEffects = node.SideEffects;
if (!sideEffects.IsEmpty)
{
foreach (var se in sideEffects)
{
VisitRvalue(se);
}
}
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitSequencePoint(BoundSequencePoint node)
{
if (node.StatementOpt != null)
{
VisitStatement(node.StatementOpt);
}
return null;
}
public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node)
{
if (node.StatementOpt != null)
{
VisitStatement(node.StatementOpt);
}
return null;
}
public override BoundNode VisitStatementList(BoundStatementList node)
{
return VisitStatementListWorker(node);
}
private BoundNode VisitStatementListWorker(BoundStatementList node)
{
foreach (var statement in node.Statements)
{
VisitStatement(statement);
}
return null;
}
public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node)
{
return VisitStatementListWorker(node);
}
public override BoundNode VisitUnboundLambda(UnboundLambda node)
{
// The presence of this node suggests an error was detected in an earlier phase.
return VisitLambda(node.BindForErrorRecovery());
}
public override BoundNode VisitBreakStatement(BoundBreakStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, node.Label));
SetUnreachable();
return null;
}
public override BoundNode VisitContinueStatement(BoundContinueStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, node.Label));
SetUnreachable();
return null;
}
public override BoundNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node)
{
return VisitConditionalOperatorCore(node, isByRef: false, node.Condition, node.Consequence, node.Alternative);
}
public override BoundNode VisitConditionalOperator(BoundConditionalOperator node)
{
return VisitConditionalOperatorCore(node, node.IsRef, node.Condition, node.Consequence, node.Alternative);
}
#nullable enable
protected virtual BoundNode? VisitConditionalOperatorCore(
BoundExpression node,
bool isByRef,
BoundExpression condition,
BoundExpression consequence,
BoundExpression alternative)
{
VisitCondition(condition);
var consequenceState = this.StateWhenTrue;
var alternativeState = this.StateWhenFalse;
if (IsConstantTrue(condition))
{
VisitConditionalOperand(alternativeState, alternative, isByRef);
VisitConditionalOperand(consequenceState, consequence, isByRef);
}
else if (IsConstantFalse(condition))
{
VisitConditionalOperand(consequenceState, consequence, isByRef);
VisitConditionalOperand(alternativeState, alternative, isByRef);
}
else
{
// at this point, the state is conditional after a conditional expression if:
// 1. the state is conditional after the consequence, or
// 2. the state is conditional after the alternative
VisitConditionalOperand(consequenceState, consequence, isByRef);
var conditionalAfterConsequence = IsConditionalState;
var (afterConsequenceWhenTrue, afterConsequenceWhenFalse) = conditionalAfterConsequence ? (StateWhenTrue, StateWhenFalse) : (State, State);
VisitConditionalOperand(alternativeState, alternative, isByRef);
if (!conditionalAfterConsequence && !IsConditionalState)
{
// simplify in the common case
Join(ref this.State, ref afterConsequenceWhenTrue);
}
else
{
Split();
Join(ref this.StateWhenTrue, ref afterConsequenceWhenTrue);
Join(ref this.StateWhenFalse, ref afterConsequenceWhenFalse);
}
}
return null;
}
#nullable disable
private void VisitConditionalOperand(TLocalState state, BoundExpression operand, bool isByRef)
{
SetState(state);
if (isByRef)
{
VisitLvalue(operand);
// exposing ref is a potential write
WriteArgument(operand, RefKind.Ref, method: null);
}
else
{
Visit(operand);
}
}
public override BoundNode VisitBaseReference(BoundBaseReference node)
{
return null;
}
public override BoundNode VisitDoStatement(BoundDoStatement node)
{
// do { statements; node.ContinueLabel: } while (node.Condition) node.BreakLabel:
LoopHead(node);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
VisitCondition(node.Condition);
TLocalState breakState = this.StateWhenFalse;
SetState(this.StateWhenTrue);
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
return null;
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, node.Label));
SetUnreachable();
return null;
}
protected void VisitLabel(LabelSymbol label, BoundStatement node)
{
node.AssertIsLabeledStatementWithLabel(label);
ResolveBranches(label, node);
var state = LabelState(label);
Join(ref this.State, ref state);
_labels[label] = this.State.Clone();
_labelsSeen.Add(node);
}
protected virtual void VisitLabel(BoundLabeledStatement node)
{
VisitLabel(node.Label, node);
}
public override BoundNode VisitLabelStatement(BoundLabelStatement node)
{
VisitLabel(node.Label, node);
return null;
}
public override BoundNode VisitLabeledStatement(BoundLabeledStatement node)
{
VisitLabel(node);
VisitStatement(node.Body);
return null;
}
public override BoundNode VisitLockStatement(BoundLockStatement node)
{
VisitRvalue(node.Argument);
VisitStatement(node.Body);
return null;
}
public override BoundNode VisitNoOpStatement(BoundNoOpStatement node)
{
return null;
}
public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node)
{
return null;
}
public override BoundNode VisitUsingStatement(BoundUsingStatement node)
{
if (node.ExpressionOpt != null)
{
VisitRvalue(node.ExpressionOpt);
}
if (node.DeclarationsOpt != null)
{
VisitStatement(node.DeclarationsOpt);
}
VisitStatement(node.Body);
if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null)
{
PendingBranches.Add(new PendingBranch(node, this.State, null));
}
return null;
}
public abstract bool AwaitUsingAndForeachAddsPendingBranch { get; }
public override BoundNode VisitFixedStatement(BoundFixedStatement node)
{
VisitStatement(node.Declarations);
VisitStatement(node.Body);
return null;
}
public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitThrowStatement(BoundThrowStatement node)
{
BoundExpression expr = node.ExpressionOpt;
VisitRvalue(expr);
SetUnreachable();
return null;
}
public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, null));
SetUnreachable();
return null;
}
public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node)
{
VisitRvalue(node.Expression);
PendingBranches.Add(new PendingBranch(node, this.State, null));
return null;
}
public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node)
{
return null;
}
public override BoundNode VisitDefaultExpression(BoundDefaultExpression node)
{
return null;
}
public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node)
{
VisitTypeExpression(node.SourceType);
return null;
}
public override BoundNode VisitNameOfOperator(BoundNameOfOperator node)
{
var savedState = this.State;
SetState(UnreachableState());
Visit(node.Argument);
SetState(savedState);
return null;
}
public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node)
{
VisitAddressOfOperand(node.Operand, shouldReadOperand: false);
return null;
}
protected void VisitAddressOfOperand(BoundExpression operand, bool shouldReadOperand)
{
if (shouldReadOperand)
{
this.VisitRvalue(operand);
}
else
{
this.VisitLvalue(operand);
}
this.WriteArgument(operand, RefKind.Out, null); //Out because we know it will definitely be assigned.
}
public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node)
{
VisitRvalue(node.Expression);
VisitRvalue(node.Index);
return null;
}
public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node)
{
return null;
}
private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node)
{
VisitRvalue(node.Count);
if (node.InitializerOpt != null && !node.InitializerOpt.Initializers.IsDefault)
{
foreach (var element in node.InitializerOpt.Initializers)
{
VisitRvalue(element);
}
}
return null;
}
public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node)
{
return VisitStackAllocArrayCreationBase(node);
}
public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node)
{
return VisitStackAllocArrayCreationBase(node);
}
public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node)
{
// visit arguments as r-values
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.Constructor);
return null;
}
public override BoundNode VisitArrayLength(BoundArrayLength node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
VisitCondition(node.Condition);
Debug.Assert(this.IsConditionalState);
if (node.JumpIfTrue)
{
PendingBranches.Add(new PendingBranch(node, this.StateWhenTrue, node.Label));
this.SetState(this.StateWhenFalse);
}
else
{
PendingBranches.Add(new PendingBranch(node, this.StateWhenFalse, node.Label));
this.SetState(this.StateWhenTrue);
}
return null;
}
public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node)
{
return VisitObjectOrCollectionInitializerExpression(node.Initializers);
}
public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node)
{
return VisitObjectOrCollectionInitializerExpression(node.Initializers);
}
private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray<BoundExpression> initializers)
{
foreach (var initializer in initializers)
{
VisitRvalue(initializer);
}
return null;
}
public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node)
{
var arguments = node.Arguments;
if (!arguments.IsDefaultOrEmpty)
{
MethodSymbol method = null;
if (node.MemberSymbol?.Kind == SymbolKind.Property)
{
var property = (PropertySymbol)node.MemberSymbol;
method = GetReadMethod(property);
}
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method);
}
return null;
}
public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node)
{
return null;
}
public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node)
{
if (node.AddMethod.CallsAreOmitted(node.SyntaxTree))
{
// If the underlying add method is a partial method without a definition, or is a conditional method
// whose condition is not true, then the call has no effect and it is ignored for the purposes of
// flow analysis.
TLocalState savedState = savedState = this.State.Clone();
SetUnreachable();
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod);
this.State = savedState;
}
else
{
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod);
}
return null;
}
public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node)
{
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), method: null);
return null;
}
public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node)
{
return null;
}
public override BoundNode VisitFieldEqualsValue(BoundFieldEqualsValue node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitParameterEqualsValue(BoundParameterEqualsValue node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node)
{
return null;
}
public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node)
{
return null;
}
public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node)
{
return null;
}
public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node)
{
throw ExceptionUtilities.Unreachable;
}
public sealed override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitDiscardExpression(BoundDiscardExpression node)
{
return null;
}
private static MethodSymbol GetReadMethod(PropertySymbol property) =>
property.GetOwnOrInheritedGetMethod() ?? property.SetMethod;
private static MethodSymbol GetWriteMethod(PropertySymbol property) =>
property.GetOwnOrInheritedSetMethod() ?? property.GetMethod;
public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node)
{
Visit(node.Initializer);
VisitMethodBodies(node.BlockBody, node.ExpressionBody);
return null;
}
public override BoundNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node)
{
VisitMethodBodies(node.BlockBody, node.ExpressionBody);
return null;
}
public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node)
{
TLocalState leftState;
if (RegularPropertyAccess(node.LeftOperand) &&
(BoundPropertyAccess)node.LeftOperand is var left &&
left.PropertySymbol is var property &&
property.RefKind == RefKind.None)
{
var readMethod = property.GetOwnOrInheritedGetMethod();
VisitReceiverBeforeCall(left.ReceiverOpt, readMethod);
VisitReceiverAfterCall(left.ReceiverOpt, readMethod);
var savedState = this.State.Clone();
AdjustStateForNullCoalescingAssignmentNonNullCase(node);
leftState = this.State.Clone();
SetState(savedState);
VisitAssignmentOfNullCoalescingAssignment(node, left);
}
else
{
VisitRvalue(node.LeftOperand, isKnownToBeAnLvalue: true);
var savedState = this.State.Clone();
AdjustStateForNullCoalescingAssignmentNonNullCase(node);
leftState = this.State.Clone();
SetState(savedState);
VisitAssignmentOfNullCoalescingAssignment(node, propertyAccessOpt: null);
}
Join(ref this.State, ref leftState);
return null;
}
public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node)
{
Visit(node.InvokedExpression);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature);
return null;
}
public override BoundNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node)
{
// This is not encountered in correct programs, but can be seen if the function pointer was
// unable to be converted and the semantic model is used to query for information.
Visit(node.Operand);
return null;
}
/// <summary>
/// This visitor represents just the assignment part of the null coalescing assignment
/// operator.
/// </summary>
protected virtual void VisitAssignmentOfNullCoalescingAssignment(
BoundNullCoalescingAssignmentOperator node,
BoundPropertyAccess propertyAccessOpt)
{
VisitRvalue(node.RightOperand);
if (propertyAccessOpt != null)
{
var symbol = propertyAccessOpt.PropertySymbol;
var writeMethod = symbol.GetOwnOrInheritedSetMethod();
PropertySetter(node, propertyAccessOpt.ReceiverOpt, writeMethod);
}
}
public override BoundNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node)
{
return null;
}
public override BoundNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node)
{
return null;
}
public override BoundNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node)
{
return null;
}
/// <summary>
/// This visitor represents just the non-assignment part of the null coalescing assignment
/// operator (when the left operand is non-null).
/// </summary>
protected virtual void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node)
{
}
private void VisitMethodBodies(BoundBlock blockBody, BoundBlock expressionBody)
{
if (blockBody == null)
{
Visit(expressionBody);
return;
}
else if (expressionBody == null)
{
Visit(blockBody);
return;
}
// In error cases we have two bodies. These are two unrelated pieces of code,
// they are not executed one after another. As we don't really know which one the developer
// intended to use, we need to visit both. We are going to pretend that there is
// an unconditional fork in execution and then we are converging after each body is executed.
// For example, if only one body assigns an out parameter, then after visiting both bodies
// we should consider that parameter is not definitely assigned.
// Note, that today this code is not executed for regular definite assignment analysis. It is
// only executed for region analysis.
TLocalState initialState = this.State.Clone();
Visit(blockBody);
TLocalState afterBlock = this.State;
SetState(initialState);
Visit(expressionBody);
Join(ref this.State, ref afterBlock);
}
#endregion visitors
}
/// <summary>
/// The possible places that we are processing when there is a region.
/// </summary>
/// <remarks>
/// This should be nested inside <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}"/> but is not due to https://github.com/dotnet/roslyn/issues/36992 .
/// </remarks>
internal enum RegionPlace { Before, Inside, After };
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// An abstract flow pass that takes some shortcuts in analyzing finally blocks, in order to enable
/// the analysis to take place without tracking exceptions or repeating the analysis of a finally block
/// for each exit from a try statement. The shortcut results in a slightly less precise
/// (but still conservative) analysis, but that less precise analysis is all that is required for
/// the language specification. The most significant shortcut is that we do not track the state
/// where exceptions can arise. That does not affect the soundness for most analyses, but for those
/// analyses whose soundness would be affected (e.g. "data flows out"), we track "unassignments" to keep
/// the analysis sound.
/// </summary>
/// <remarks>
/// Formally, this is a fairly conventional lattice flow analysis (<see
/// href="https://en.wikipedia.org/wiki/Data-flow_analysis"/>) that moves upward through the <see cref="Join(ref
/// TLocalState, ref TLocalState)"/> operation.
/// </remarks>
internal abstract partial class AbstractFlowPass<TLocalState, TLocalFunctionState> : BoundTreeVisitor
where TLocalState : AbstractFlowPass<TLocalState, TLocalFunctionState>.ILocalState
where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState
{
protected int _recursionDepth;
/// <summary>
/// The compilation in which the analysis is taking place. This is needed to determine which
/// conditional methods will be compiled and which will be omitted.
/// </summary>
protected readonly CSharpCompilation compilation;
/// <summary>
/// The method whose body is being analyzed, or the field whose initializer is being analyzed.
/// May be a top-level member or a lambda or local function. It is used for
/// references to method parameters. Thus, '_symbol' should not be used directly, but
/// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used
/// instead. _symbol is null during speculative binding.
/// </summary>
protected readonly Symbol _symbol;
/// <summary>
/// Reflects the enclosing member, lambda or local function at the current location (in the bound tree).
/// </summary>
protected Symbol CurrentSymbol;
/// <summary>
/// The bound node of the method or initializer being analyzed.
/// </summary>
protected readonly BoundNode methodMainNode;
/// <summary>
/// The flow analysis state at each label, computed by calling <see cref="Join(ref
/// TLocalState, ref TLocalState)"/> on the state from branches to that label with the state
/// when we fall into the label. Entries are created when the label is encountered. One
/// case deserves special attention: when the destination of the branch is a label earlier
/// in the code, it is possible (though rarely occurs in practice) that we are changing the
/// state at a label that we've already analyzed. In that case we run another pass of the
/// analysis to allow those changes to propagate. This repeats until no further changes to
/// the state of these labels occurs. This can result in quadratic performance in unlikely
/// but possible code such as this: "int x; if (cond) goto l1; x = 3; l5: print x; l4: goto
/// l5; l3: goto l4; l2: goto l3; l1: goto l2;"
/// </summary>
private readonly PooledDictionary<LabelSymbol, TLocalState> _labels;
/// <summary>
/// Set to true after an analysis scan if the analysis was incomplete due to state changing
/// after it was used by another analysis component. In this case the caller scans again (until
/// this is false). Since the analysis proceeds by monotonically changing the state computed
/// at each label, this must terminate.
/// </summary>
protected bool stateChangedAfterUse;
/// <summary>
/// All of the labels seen so far in this forward scan of the body
/// </summary>
private PooledHashSet<BoundStatement> _labelsSeen;
/// <summary>
/// Pending escapes generated in the current scope (or more deeply nested scopes). When jump
/// statements (goto, break, continue, return) are processed, they are placed in the
/// pendingBranches buffer to be processed later by the code handling the destination
/// statement. As a special case, the processing of try-finally statements might modify the
/// contents of the pendingBranches buffer to take into account the behavior of
/// "intervening" finally clauses.
/// </summary>
protected ArrayBuilder<PendingBranch> PendingBranches { get; private set; }
/// <summary>
/// The definite assignment and/or reachability state at the point currently being analyzed.
/// </summary>
protected TLocalState State;
protected TLocalState StateWhenTrue;
protected TLocalState StateWhenFalse;
protected bool IsConditionalState;
/// <summary>
/// Indicates that the transfer function for a particular node (the function mapping the
/// state before the node to the state after the node) is not monotonic, in the sense that
/// it can change the state in either direction in the lattice. If the transfer function is
/// monotonic, the transfer function can only change the state toward the <see
/// cref="UnreachableState"/>. Reachability and definite assignment are monotonic, and
/// permit a more efficient analysis. Region analysis and nullable analysis are not
/// monotonic. This is just an optimization; we could treat all of them as nonmonotonic
/// without much loss of performance. In fact, this only affects the analysis of (relatively
/// rare) try statements, and is only a slight optimization.
/// </summary>
private readonly bool _nonMonotonicTransfer;
protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state)
{
SetConditionalState(state.whenTrue, state.whenFalse);
}
protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse)
{
IsConditionalState = true;
State = default(TLocalState);
StateWhenTrue = whenTrue;
StateWhenFalse = whenFalse;
}
protected void SetState(TLocalState newState)
{
Debug.Assert(newState != null);
StateWhenTrue = StateWhenFalse = default(TLocalState);
IsConditionalState = false;
State = newState;
}
protected void Split()
{
if (!IsConditionalState)
{
SetConditionalState(State, State.Clone());
}
}
protected void Unsplit()
{
if (IsConditionalState)
{
Join(ref StateWhenTrue, ref StateWhenFalse);
SetState(StateWhenTrue);
}
}
/// <summary>
/// Where all diagnostics are deposited.
/// </summary>
protected DiagnosticBag Diagnostics { get; }
#region Region
// For region analysis, we maintain some extra data.
protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region
protected readonly BoundNode firstInRegion, lastInRegion;
protected readonly bool TrackingRegions;
/// <summary>
/// A cache of the state at the backward branch point of each loop. This is not needed
/// during normal flow analysis, but is needed for DataFlowsOut region analysis.
/// </summary>
private readonly Dictionary<BoundLoopStatement, TLocalState> _loopHeadState;
#endregion Region
protected AbstractFlowPass(
CSharpCompilation compilation,
Symbol symbol,
BoundNode node,
BoundNode firstInRegion = null,
BoundNode lastInRegion = null,
bool trackRegions = false,
bool nonMonotonicTransferFunction = false)
{
Debug.Assert(node != null);
if (firstInRegion != null && lastInRegion != null)
{
trackRegions = true;
}
if (trackRegions)
{
Debug.Assert(firstInRegion != null);
Debug.Assert(lastInRegion != null);
int startLocation = firstInRegion.Syntax.SpanStart;
int endLocation = lastInRegion.Syntax.Span.End;
int length = endLocation - startLocation;
Debug.Assert(length >= 0, "last comes before first");
this.RegionSpan = new TextSpan(startLocation, length);
}
PendingBranches = ArrayBuilder<PendingBranch>.GetInstance();
_labelsSeen = PooledHashSet<BoundStatement>.GetInstance();
_labels = PooledDictionary<LabelSymbol, TLocalState>.GetInstance();
this.Diagnostics = DiagnosticBag.GetInstance();
this.compilation = compilation;
_symbol = symbol;
CurrentSymbol = symbol;
this.methodMainNode = node;
this.firstInRegion = firstInRegion;
this.lastInRegion = lastInRegion;
_loopHeadState = new Dictionary<BoundLoopStatement, TLocalState>(ReferenceEqualityComparer.Instance);
TrackingRegions = trackRegions;
_nonMonotonicTransfer = nonMonotonicTransferFunction;
}
protected abstract string Dump(TLocalState state);
protected string Dump()
{
return IsConditionalState
? $"true: {Dump(this.StateWhenTrue)} false: {Dump(this.StateWhenFalse)}"
: Dump(this.State);
}
#if DEBUG
protected string DumpLabels()
{
StringBuilder result = new StringBuilder();
result.Append("Labels{");
bool first = true;
foreach (var key in _labels.Keys)
{
if (!first)
{
result.Append(", ");
}
string name = key.Name;
if (string.IsNullOrEmpty(name))
{
name = "<Label>" + key.GetHashCode();
}
result.Append(name).Append(": ").Append(this.Dump(_labels[key]));
first = false;
}
result.Append("}");
return result.ToString();
}
#endif
private void EnterRegionIfNeeded(BoundNode node)
{
if (TrackingRegions && node == this.firstInRegion && this.regionPlace == RegionPlace.Before)
{
EnterRegion();
}
}
/// <summary>
/// Subclasses may override EnterRegion to perform any actions at the entry to the region.
/// </summary>
protected virtual void EnterRegion()
{
Debug.Assert(this.regionPlace == RegionPlace.Before);
this.regionPlace = RegionPlace.Inside;
}
private void LeaveRegionIfNeeded(BoundNode node)
{
if (TrackingRegions && node == this.lastInRegion && this.regionPlace == RegionPlace.Inside)
{
LeaveRegion();
}
}
/// <summary>
/// Subclasses may override LeaveRegion to perform any action at the end of the region.
/// </summary>
protected virtual void LeaveRegion()
{
Debug.Assert(IsInside);
this.regionPlace = RegionPlace.After;
}
protected readonly TextSpan RegionSpan;
protected bool RegionContains(TextSpan span)
{
// TODO: There are no scenarios involving a zero-length span
// currently. If the assert fails, add a corresponding test.
Debug.Assert(span.Length > 0);
if (span.Length == 0)
{
return RegionSpan.Contains(span.Start);
}
return RegionSpan.Contains(span);
}
protected bool IsInside
{
get
{
return regionPlace == RegionPlace.Inside;
}
}
protected virtual void EnterParameters(ImmutableArray<ParameterSymbol> parameters)
{
foreach (var parameter in parameters)
{
EnterParameter(parameter);
}
}
protected virtual void EnterParameter(ParameterSymbol parameter)
{ }
protected virtual void LeaveParameters(
ImmutableArray<ParameterSymbol> parameters,
SyntaxNode syntax,
Location location)
{
foreach (ParameterSymbol parameter in parameters)
{
LeaveParameter(parameter, syntax, location);
}
}
protected virtual void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location)
{ }
public override BoundNode Visit(BoundNode node)
{
return VisitAlways(node);
}
protected BoundNode VisitAlways(BoundNode node)
{
BoundNode result = null;
// We scan even expressions, because we must process lambdas contained within them.
if (node != null)
{
EnterRegionIfNeeded(node);
VisitWithStackGuard(node);
LeaveRegionIfNeeded(node);
}
return result;
}
[DebuggerStepThrough]
private BoundNode VisitWithStackGuard(BoundNode node)
{
var expression = node as BoundExpression;
if (expression != null)
{
return VisitExpressionWithStackGuard(ref _recursionDepth, expression);
}
return base.Visit(node);
}
[DebuggerStepThrough]
protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node)
{
return (BoundExpression)base.Visit(node);
}
protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()
{
return false; // just let the original exception bubble up.
}
/// <summary>
/// A pending branch. These are created for a return, break, continue, goto statement,
/// yield return, yield break, await expression, and await foreach/using. The idea is that
/// we don't know if the branch will eventually reach its destination because of an
/// intervening finally block that cannot complete normally. So we store them up and handle
/// them as we complete processing each construct. At the end of a block, if there are any
/// pending branches to a label in that block we process the branch. Otherwise we relay it
/// up to the enclosing construct as a pending branch of the enclosing construct.
/// </summary>
internal class PendingBranch
{
public readonly BoundNode Branch;
public bool IsConditionalState;
public TLocalState State;
public TLocalState StateWhenTrue;
public TLocalState StateWhenFalse;
public readonly LabelSymbol Label;
public PendingBranch(BoundNode branch, TLocalState state, LabelSymbol label, bool isConditionalState = false, TLocalState stateWhenTrue = default, TLocalState stateWhenFalse = default)
{
this.Branch = branch;
this.State = state.Clone();
this.IsConditionalState = isConditionalState;
if (isConditionalState)
{
this.StateWhenTrue = stateWhenTrue.Clone();
this.StateWhenFalse = stateWhenFalse.Clone();
}
this.Label = label;
}
}
/// <summary>
/// Perform a single pass of flow analysis. Note that after this pass,
/// this.backwardBranchChanged indicates if a further pass is required.
/// </summary>
protected virtual ImmutableArray<PendingBranch> Scan(ref bool badRegion)
{
var oldPending = SavePending();
Visit(methodMainNode);
this.Unsplit();
RestorePending(oldPending);
if (TrackingRegions && regionPlace != RegionPlace.After)
{
badRegion = true;
}
ImmutableArray<PendingBranch> result = RemoveReturns();
return result;
}
protected ImmutableArray<PendingBranch> Analyze(ref bool badRegion, Optional<TLocalState> initialState = default)
{
ImmutableArray<PendingBranch> returns;
do
{
// the entry point of a method is assumed reachable
regionPlace = RegionPlace.Before;
this.State = initialState.HasValue ? initialState.Value : TopState();
PendingBranches.Clear();
this.stateChangedAfterUse = false;
this.Diagnostics.Clear();
returns = this.Scan(ref badRegion);
}
while (this.stateChangedAfterUse);
return returns;
}
protected virtual void Free()
{
this.Diagnostics.Free();
PendingBranches.Free();
_labelsSeen.Free();
_labels.Free();
}
/// <summary>
/// If a method is currently being analyzed returns its parameters, returns an empty array
/// otherwise.
/// </summary>
protected ImmutableArray<ParameterSymbol> MethodParameters
{
get
{
var method = _symbol as MethodSymbol;
return (object)method == null ? ImmutableArray<ParameterSymbol>.Empty : method.Parameters;
}
}
/// <summary>
/// If a method is currently being analyzed returns its 'this' parameter, returns null
/// otherwise.
/// </summary>
protected ParameterSymbol MethodThisParameter
{
get
{
ParameterSymbol thisParameter = null;
(_symbol as MethodSymbol)?.TryGetThisParameter(out thisParameter);
return thisParameter;
}
}
/// <summary>
/// Specifies whether or not method's out parameters should be analyzed. If there's more
/// than one location in the method being analyzed, then the method is partial and we prefer
/// to report an out parameter in partial method error.
/// </summary>
/// <param name="location">location to be used</param>
/// <returns>true if the out parameters of the method should be analyzed</returns>
protected bool ShouldAnalyzeOutParameters(out Location location)
{
var method = _symbol as MethodSymbol;
if ((object)method == null || method.Locations.Length != 1)
{
location = null;
return false;
}
else
{
location = method.Locations[0];
return true;
}
}
/// <summary>
/// Return the flow analysis state associated with a label.
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
protected virtual TLocalState LabelState(LabelSymbol label)
{
TLocalState result;
if (_labels.TryGetValue(label, out result))
{
return result;
}
result = UnreachableState();
_labels.Add(label, result);
return result;
}
/// <summary>
/// Return to the caller the set of pending return statements.
/// </summary>
/// <returns></returns>
protected virtual ImmutableArray<PendingBranch> RemoveReturns()
{
ImmutableArray<PendingBranch> result;
result = PendingBranches.ToImmutable();
PendingBranches.Clear();
// The caller should have handled and cleared labelsSeen.
Debug.Assert(_labelsSeen.Count == 0);
return result;
}
/// <summary>
/// Set the current state to one that indicates that it is unreachable.
/// </summary>
protected void SetUnreachable()
{
this.State = UnreachableState();
}
protected void VisitLvalue(BoundExpression node)
{
EnterRegionIfNeeded(node);
switch (node?.Kind)
{
case BoundKind.Parameter:
VisitLvalueParameter((BoundParameter)node);
break;
case BoundKind.Local:
VisitLvalue((BoundLocal)node);
break;
case BoundKind.ThisReference:
case BoundKind.BaseReference:
break;
case BoundKind.PropertyAccess:
var access = (BoundPropertyAccess)node;
if (Binder.AccessingAutoPropertyFromConstructor(access, _symbol))
{
var backingField = (access.PropertySymbol as SourcePropertySymbolBase)?.BackingField;
if (backingField != null)
{
VisitFieldAccessInternal(access.ReceiverOpt, backingField);
break;
}
}
goto default;
case BoundKind.FieldAccess:
{
BoundFieldAccess node1 = (BoundFieldAccess)node;
VisitFieldAccessInternal(node1.ReceiverOpt, node1.FieldSymbol);
break;
}
case BoundKind.EventAccess:
{
BoundEventAccess node1 = (BoundEventAccess)node;
VisitFieldAccessInternal(node1.ReceiverOpt, node1.EventSymbol.AssociatedField);
break;
}
case BoundKind.TupleLiteral:
case BoundKind.ConvertedTupleLiteral:
((BoundTupleExpression)node).VisitAllElements((x, self) => self.VisitLvalue(x), this);
break;
default:
VisitRvalue(node);
break;
}
LeaveRegionIfNeeded(node);
}
protected virtual void VisitLvalue(BoundLocal node)
{
}
/// <summary>
/// Visit a boolean condition expression.
/// </summary>
/// <param name="node"></param>
protected void VisitCondition(BoundExpression node)
{
Visit(node);
AdjustConditionalState(node);
}
private void AdjustConditionalState(BoundExpression node)
{
if (IsConstantTrue(node))
{
Unsplit();
SetConditionalState(this.State, UnreachableState());
}
else if (IsConstantFalse(node))
{
Unsplit();
SetConditionalState(UnreachableState(), this.State);
}
else if ((object)node.Type == null || node.Type.SpecialType != SpecialType.System_Boolean)
{
// a dynamic type or a type with operator true/false
Unsplit();
}
Split();
}
/// <summary>
/// Visit a general expression, where we will only need to determine if variables are
/// assigned (or not). That is, we will not be needing AssignedWhenTrue and
/// AssignedWhenFalse.
/// </summary>
/// <param name="isKnownToBeAnLvalue">True when visiting an rvalue that will actually be used as an lvalue,
/// for example a ref parameter when simulating a read of it, or an argument corresponding to an in parameter</param>
protected virtual void VisitRvalue(BoundExpression node, bool isKnownToBeAnLvalue = false)
{
Visit(node);
Unsplit();
}
/// <summary>
/// Visit a statement.
/// </summary>
[DebuggerHidden]
protected virtual void VisitStatement(BoundStatement statement)
{
Visit(statement);
Debug.Assert(!this.IsConditionalState);
}
protected static bool IsConstantTrue(BoundExpression node)
{
return node.ConstantValue == ConstantValue.True;
}
protected static bool IsConstantFalse(BoundExpression node)
{
return node.ConstantValue == ConstantValue.False;
}
protected static bool IsConstantNull(BoundExpression node)
{
return node.ConstantValue == ConstantValue.Null;
}
/// <summary>
/// Called at the point in a loop where the backwards branch would go to.
/// </summary>
private void LoopHead(BoundLoopStatement node)
{
TLocalState previousState;
if (_loopHeadState.TryGetValue(node, out previousState))
{
Join(ref this.State, ref previousState);
}
_loopHeadState[node] = this.State.Clone();
}
/// <summary>
/// Called at the point in a loop where the backward branch is placed.
/// </summary>
private void LoopTail(BoundLoopStatement node)
{
var oldState = _loopHeadState[node];
if (Join(ref oldState, ref this.State))
{
_loopHeadState[node] = oldState;
this.stateChangedAfterUse = true;
}
}
/// <summary>
/// Used to resolve break statements in each statement form that has a break statement
/// (loops, switch).
/// </summary>
private void ResolveBreaks(TLocalState breakState, LabelSymbol label)
{
var pendingBranches = PendingBranches;
var count = pendingBranches.Count;
if (count != 0)
{
int stillPending = 0;
for (int i = 0; i < count; i++)
{
var pending = pendingBranches[i];
if (pending.Label == label)
{
Join(ref breakState, ref pending.State);
}
else
{
if (stillPending != i)
{
pendingBranches[stillPending] = pending;
}
stillPending++;
}
}
pendingBranches.Clip(stillPending);
}
SetState(breakState);
}
/// <summary>
/// Used to resolve continue statements in each statement form that supports it.
/// </summary>
private void ResolveContinues(LabelSymbol continueLabel)
{
var pendingBranches = PendingBranches;
var count = pendingBranches.Count;
if (count != 0)
{
int stillPending = 0;
for (int i = 0; i < count; i++)
{
var pending = pendingBranches[i];
if (pending.Label == continueLabel)
{
// Technically, nothing in the language specification depends on the state
// at the continue label, so we could just discard them instead of merging
// the states. In fact, we need not have added continue statements to the
// pending jump queue in the first place if we were interested solely in the
// flow analysis. However, region analysis (in support of extract method)
// and other forms of more precise analysis
// depend on continue statements appearing in the pending branch queue, so
// we process them from the queue here.
Join(ref this.State, ref pending.State);
}
else
{
if (stillPending != i)
{
pendingBranches[stillPending] = pending;
}
stillPending++;
}
}
pendingBranches.Clip(stillPending);
}
}
/// <summary>
/// Subclasses override this if they want to take special actions on processing a goto
/// statement, when both the jump and the label have been located.
/// </summary>
protected virtual void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement target)
{
target.AssertIsLabeledStatement();
}
/// <summary>
/// To handle a label, we resolve all branches to that label. Returns true if the state of
/// the label changes as a result.
/// </summary>
/// <param name="label">Target label</param>
/// <param name="target">Statement containing the target label</param>
private bool ResolveBranches(LabelSymbol label, BoundStatement target)
{
target?.AssertIsLabeledStatementWithLabel(label);
bool labelStateChanged = false;
var pendingBranches = PendingBranches;
var count = pendingBranches.Count;
if (count != 0)
{
int stillPending = 0;
for (int i = 0; i < count; i++)
{
var pending = pendingBranches[i];
if (pending.Label == label)
{
ResolveBranch(pending, label, target, ref labelStateChanged);
}
else
{
if (stillPending != i)
{
pendingBranches[stillPending] = pending;
}
stillPending++;
}
}
pendingBranches.Clip(stillPending);
}
return labelStateChanged;
}
protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged)
{
var state = LabelState(label);
if (target != null)
{
NoteBranch(pending, pending.Branch, target);
}
var changed = Join(ref state, ref pending.State);
if (changed)
{
labelStateChanged = true;
_labels[label] = state;
}
}
protected struct SavedPending
{
public readonly ArrayBuilder<PendingBranch> PendingBranches;
public readonly PooledHashSet<BoundStatement> LabelsSeen;
public SavedPending(ArrayBuilder<PendingBranch> pendingBranches, PooledHashSet<BoundStatement> labelsSeen)
{
this.PendingBranches = pendingBranches;
this.LabelsSeen = labelsSeen;
}
}
/// <summary>
/// Since branches cannot branch into constructs, only out, we save the pending branches
/// when visiting more nested constructs. When tracking exceptions, we store the current
/// state as the exception state for the following code.
/// </summary>
protected SavedPending SavePending()
{
Debug.Assert(!this.IsConditionalState);
var result = new SavedPending(PendingBranches, _labelsSeen);
PendingBranches = ArrayBuilder<PendingBranch>.GetInstance();
_labelsSeen = PooledHashSet<BoundStatement>.GetInstance();
return result;
}
/// <summary>
/// We use this when closing a block that may contain labels or branches
/// - branches to new labels are resolved
/// - new labels are removed (no longer can be reached)
/// - unresolved pending branches are carried forward
/// </summary>
/// <param name="oldPending">The old pending branches, which are to be merged with the current ones</param>
protected void RestorePending(SavedPending oldPending)
{
foreach (var node in _labelsSeen)
{
switch (node.Kind)
{
case BoundKind.LabeledStatement:
{
var label = (BoundLabeledStatement)node;
stateChangedAfterUse |= ResolveBranches(label.Label, label);
}
break;
case BoundKind.LabelStatement:
{
var label = (BoundLabelStatement)node;
stateChangedAfterUse |= ResolveBranches(label.Label, label);
}
break;
case BoundKind.SwitchSection:
{
var sec = (BoundSwitchSection)node;
foreach (var label in sec.SwitchLabels)
{
stateChangedAfterUse |= ResolveBranches(label.Label, sec);
}
}
break;
default:
// there are no other kinds of labels
throw ExceptionUtilities.UnexpectedValue(node.Kind);
}
}
oldPending.PendingBranches.AddRange(this.PendingBranches);
PendingBranches.Free();
PendingBranches = oldPending.PendingBranches;
// We only use SavePending/RestorePending when there could be no branch into the region between them.
// So there is no need to save the labels seen between the calls. If there were such a need, we would
// do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment
_labelsSeen.Free();
_labelsSeen = oldPending.LabelsSeen;
}
#region visitors
/// <summary>
/// Since each language construct must be handled according to the rules of the language specification,
/// the default visitor reports that the construct for the node is not implemented in the compiler.
/// </summary>
public override BoundNode DefaultVisit(BoundNode node)
{
Debug.Assert(false, $"Should Visit{node.Kind} be overridden in {this.GetType().Name}?");
Diagnostics.Add(ErrorCode.ERR_InternalError, node.Syntax.Location);
return null;
}
public override BoundNode VisitAttribute(BoundAttribute node)
{
// No flow analysis is ever done in attributes (or their arguments).
return null;
}
public override BoundNode VisitThrowExpression(BoundThrowExpression node)
{
VisitRvalue(node.Expression);
SetUnreachable();
return node;
}
public override BoundNode VisitPassByCopy(BoundPassByCopy node)
{
VisitRvalue(node.Expression);
return node;
}
public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node)
{
Debug.Assert(!IsConditionalState);
bool negated = node.Pattern.IsNegated(out var pattern);
Debug.Assert(negated == node.IsNegated);
if (VisitPossibleConditionalAccess(node.Expression, out var stateWhenNotNull))
{
Debug.Assert(!IsConditionalState);
SetConditionalState(patternMatchesNull(pattern)
? (State, stateWhenNotNull)
: (stateWhenNotNull, State));
}
else if (IsConditionalState)
{
// Patterns which only match a single boolean value should propagate conditional state
// for example, `(a != null && a.M(out x)) is true` should have the same conditional state as `(a != null && a.M(out x))`.
if (isBoolTest(pattern) is bool value)
{
if (!value)
{
SetConditionalState(StateWhenFalse, StateWhenTrue);
}
}
else
{
// Patterns which match more than a single boolean value cannot propagate conditional state
// for example, `(a != null && a.M(out x)) is bool b` should not have conditional state
Unsplit();
}
}
VisitPattern(pattern);
var reachableLabels = node.DecisionDag.ReachableLabels;
if (!reachableLabels.Contains(node.WhenTrueLabel))
{
SetState(this.StateWhenFalse);
SetConditionalState(UnreachableState(), this.State);
}
else if (!reachableLabels.Contains(node.WhenFalseLabel))
{
SetState(this.StateWhenTrue);
SetConditionalState(this.State, UnreachableState());
}
if (negated)
{
SetConditionalState(this.StateWhenFalse, this.StateWhenTrue);
}
return node;
static bool patternMatchesNull(BoundPattern pattern)
{
switch (pattern)
{
case BoundTypePattern:
case BoundRecursivePattern:
case BoundITuplePattern:
case BoundRelationalPattern:
case BoundDeclarationPattern { IsVar: false }:
case BoundConstantPattern { ConstantValue: { IsNull: false } }:
return false;
case BoundConstantPattern { ConstantValue: { IsNull: true } }:
return true;
case BoundNegatedPattern negated:
return !patternMatchesNull(negated.Negated);
case BoundBinaryPattern binary:
if (binary.Disjunction)
{
// `a?.b(out x) is null or C`
// pattern matches null if either subpattern matches null
var leftNullTest = patternMatchesNull(binary.Left);
return patternMatchesNull(binary.Left) || patternMatchesNull(binary.Right);
}
// `a?.b out x is not null and var c`
// pattern matches null only if both subpatterns match null
return patternMatchesNull(binary.Left) && patternMatchesNull(binary.Right);
case BoundDeclarationPattern { IsVar: true }:
case BoundDiscardPattern:
return true;
default:
throw ExceptionUtilities.UnexpectedValue(pattern.Kind);
}
}
// Returns `true` if the pattern only matches a `true` input.
// Returns `false` if the pattern only matches a `false` input.
// Otherwise, returns `null`.
static bool? isBoolTest(BoundPattern pattern)
{
switch (pattern)
{
case BoundConstantPattern { ConstantValue: { IsBoolean: true, BooleanValue: var boolValue } }:
return boolValue;
case BoundNegatedPattern negated:
return !isBoolTest(negated.Negated);
case BoundBinaryPattern binary:
if (binary.Disjunction)
{
// `(a != null && a.b(out x)) is true or true` matches `true`
// `(a != null && a.b(out x)) is true or false` matches any boolean
// both subpatterns must have the same bool test for the test to propagate out
var leftNullTest = isBoolTest(binary.Left);
return leftNullTest is null ? null :
leftNullTest != isBoolTest(binary.Right) ? null :
leftNullTest;
}
// `(a != null && a.b(out x)) is true and true` matches `true`
// `(a != null && a.b(out x)) is true and var x` matches `true`
// `(a != null && a.b(out x)) is true and false` never matches and is a compile error
return isBoolTest(binary.Left) ?? isBoolTest(binary.Right);
case BoundConstantPattern { ConstantValue: { IsBoolean: false } }:
case BoundDiscardPattern:
case BoundTypePattern:
case BoundRecursivePattern:
case BoundITuplePattern:
case BoundRelationalPattern:
case BoundDeclarationPattern:
return null;
default:
throw ExceptionUtilities.UnexpectedValue(pattern.Kind);
}
}
}
public virtual void VisitPattern(BoundPattern pattern)
{
Split();
}
public override BoundNode VisitConstantPattern(BoundConstantPattern node)
{
// All patterns are handled by VisitPattern
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitTupleLiteral(BoundTupleLiteral node)
{
return VisitTupleExpression(node);
}
public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node)
{
return VisitTupleExpression(node);
}
private BoundNode VisitTupleExpression(BoundTupleExpression node)
{
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), null);
return null;
}
public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node)
{
VisitRvalue(node.Left);
VisitRvalue(node.Right);
return null;
}
public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node)
{
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node)
{
VisitRvalue(node.Receiver);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
return null;
}
public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node)
{
VisitRvalue(node.Receiver);
return null;
}
public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node)
{
VisitRvalue(node.Expression);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
return null;
}
protected BoundNode VisitInterpolatedStringBase(BoundInterpolatedStringBase node, InterpolatedStringHandlerData? data)
{
// If there can be any branching, then we need to treat the expressions
// as optionally evaluated. Otherwise, we treat them as always evaluated
switch (data)
{
case null:
visitParts();
break;
case { HasTrailingHandlerValidityParameter: false, UsesBoolReturns: false, Construction: var construction }:
VisitRvalue(construction);
visitParts();
break;
case { UsesBoolReturns: var usesBoolReturns, HasTrailingHandlerValidityParameter: var hasTrailingValidityParameter, Construction: var construction }:
VisitRvalue(construction);
if (node.Parts.IsEmpty)
{
break;
}
TLocalState beforePartsState;
ReadOnlySpan<BoundExpression> remainingParts;
if (hasTrailingValidityParameter)
{
beforePartsState = State.Clone();
remainingParts = node.Parts.AsSpan();
}
else
{
Visit(node.Parts[0]);
beforePartsState = State.Clone();
remainingParts = node.Parts.AsSpan()[1..];
}
foreach (var expr in remainingParts)
{
VisitRvalue(expr);
if (usesBoolReturns)
{
Join(ref beforePartsState, ref State);
}
}
if (usesBoolReturns)
{
// Already been joined after the last part, just assign
State = beforePartsState;
}
else
{
Debug.Assert(hasTrailingValidityParameter);
Join(ref State, ref beforePartsState);
}
break;
}
return null;
void visitParts()
{
foreach (var expr in node.Parts)
{
VisitRvalue(expr);
}
}
}
public override BoundNode VisitInterpolatedString(BoundInterpolatedString node)
{
return VisitInterpolatedStringBase(node, node.InterpolationData);
}
public override BoundNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node)
{
// If the node is unconverted, we'll just treat it as if the contents are always evaluated
return VisitInterpolatedStringBase(node, data: null);
}
public override BoundNode VisitStringInsert(BoundStringInsert node)
{
VisitRvalue(node.Value);
if (node.Alignment != null)
{
VisitRvalue(node.Alignment);
}
if (node.Format != null)
{
VisitRvalue(node.Format);
}
return null;
}
public override BoundNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node)
{
return null;
}
public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node)
{
return null;
}
public override BoundNode VisitArgList(BoundArgList node)
{
// The "__arglist" expression that is legal inside a varargs method has no
// effect on flow analysis and it has no children.
return null;
}
public override BoundNode VisitArgListOperator(BoundArgListOperator node)
{
// When we have M(__arglist(x, y, z)) we must visit x, y and z.
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null);
return null;
}
public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node)
{
// Note that we require that the variable whose reference we are taking
// has been initialized; it is similar to passing the variable as a ref parameter.
VisitRvalue(node.Operand, isKnownToBeAnLvalue: true);
return null;
}
public override BoundNode VisitRefValueOperator(BoundRefValueOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node)
{
VisitStatement(node.Statement);
return null;
}
public override BoundNode VisitLambda(BoundLambda node) => null;
public override BoundNode VisitLocal(BoundLocal node)
{
SplitIfBooleanConstant(node);
return null;
}
public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node)
{
if (node.InitializerOpt != null)
{
// analyze the expression
VisitRvalue(node.InitializerOpt, isKnownToBeAnLvalue: node.LocalSymbol.RefKind != RefKind.None);
// byref assignment is also a potential write
if (node.LocalSymbol.RefKind != RefKind.None)
{
WriteArgument(node.InitializerOpt, node.LocalSymbol.RefKind, method: null);
}
}
return null;
}
public override BoundNode VisitBlock(BoundBlock node)
{
VisitStatements(node.Statements);
return null;
}
private void VisitStatements(ImmutableArray<BoundStatement> statements)
{
foreach (var statement in statements)
{
VisitStatement(statement);
}
}
public override BoundNode VisitScope(BoundScope node)
{
VisitStatements(node.Statements);
return null;
}
public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitCall(BoundCall node)
{
// If the method being called is a partial method without a definition, or is a conditional method
// whose condition is not true, then the call has no effect and it is ignored for the purposes of
// definite assignment analysis.
bool callsAreOmitted = node.Method.CallsAreOmitted(node.SyntaxTree);
TLocalState savedState = default(TLocalState);
if (callsAreOmitted)
{
savedState = this.State.Clone();
SetUnreachable();
}
VisitReceiverBeforeCall(node.ReceiverOpt, node.Method);
VisitArgumentsBeforeCall(node.Arguments, node.ArgumentRefKindsOpt);
if (node.Method?.OriginalDefinition is LocalFunctionSymbol localFunc)
{
VisitLocalFunctionUse(localFunc, node.Syntax, isCall: true);
}
VisitArgumentsAfterCall(node.Arguments, node.ArgumentRefKindsOpt, node.Method);
VisitReceiverAfterCall(node.ReceiverOpt, node.Method);
if (callsAreOmitted)
{
this.State = savedState;
}
return null;
}
protected void VisitLocalFunctionUse(LocalFunctionSymbol symbol, SyntaxNode syntax, bool isCall)
{
var localFuncState = GetOrCreateLocalFuncUsages(symbol);
VisitLocalFunctionUse(symbol, localFuncState, syntax, isCall);
}
protected virtual void VisitLocalFunctionUse(
LocalFunctionSymbol symbol,
TLocalFunctionState localFunctionState,
SyntaxNode syntax,
bool isCall)
{
if (isCall)
{
Join(ref State, ref localFunctionState.StateFromBottom);
Meet(ref State, ref localFunctionState.StateFromTop);
}
localFunctionState.Visited = true;
}
private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method)
{
if (method is null || method.MethodKind != MethodKind.Constructor)
{
VisitRvalue(receiverOpt);
}
}
private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method)
{
if (receiverOpt is null)
{
return;
}
if (method is null)
{
WriteArgument(receiverOpt, RefKind.Ref, method: null);
}
else if (method.TryGetThisParameter(out var thisParameter)
&& thisParameter is object
&& !TypeIsImmutable(thisParameter.Type))
{
var thisRefKind = thisParameter.RefKind;
if (thisRefKind.IsWritableReference())
{
WriteArgument(receiverOpt, thisRefKind, method);
}
}
}
/// <summary>
/// Certain (struct) types are known by the compiler to be immutable. In these cases calling a method on
/// the type is known (by flow analysis) not to write the receiver.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private static bool TypeIsImmutable(TypeSymbol t)
{
switch (t.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_DateTime:
return true;
default:
return t.IsNullableType();
}
}
public override BoundNode VisitIndexerAccess(BoundIndexerAccess node)
{
var method = GetReadMethod(node.Indexer);
VisitReceiverBeforeCall(node.ReceiverOpt, method);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method);
if ((object)method != null)
{
VisitReceiverAfterCall(node.ReceiverOpt, method);
}
return null;
}
public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node)
{
// Index or Range pattern indexers evaluate the following in order:
// 1. The receiver
// 1. The Count or Length method off the receiver
// 2. The argument to the access
// 3. The pattern method
VisitRvalue(node.Receiver);
var method = GetReadMethod(node.LengthOrCountProperty);
VisitReceiverAfterCall(node.Receiver, method);
VisitRvalue(node.Argument);
method = node.PatternSymbol switch
{
PropertySymbol p => GetReadMethod(p),
MethodSymbol m => m,
_ => throw ExceptionUtilities.UnexpectedValue(node.PatternSymbol)
};
VisitReceiverAfterCall(node.Receiver, method);
return null;
}
public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node)
{
VisitRvalue(node.ReceiverOpt);
VisitRvalue(node.Argument);
return null;
}
/// <summary>
/// Do not call for a local function.
/// </summary>
protected virtual void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method)
{
Debug.Assert(method?.OriginalDefinition.MethodKind != MethodKind.LocalFunction);
VisitArgumentsBeforeCall(arguments, refKindsOpt);
VisitArgumentsAfterCall(arguments, refKindsOpt, method);
}
private void VisitArgumentsBeforeCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt)
{
// first value and ref parameters are read...
for (int i = 0; i < arguments.Length; i++)
{
RefKind refKind = GetRefKind(refKindsOpt, i);
if (refKind != RefKind.Out)
{
VisitRvalue(arguments[i], isKnownToBeAnLvalue: refKind != RefKind.None);
}
else
{
VisitLvalue(arguments[i]);
}
}
}
/// <summary>
/// Writes ref and out parameters
/// </summary>
private void VisitArgumentsAfterCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method)
{
for (int i = 0; i < arguments.Length; i++)
{
RefKind refKind = GetRefKind(refKindsOpt, i);
// passing as a byref argument is also a potential write
if (refKind != RefKind.None)
{
WriteArgument(arguments[i], refKind, method);
}
}
}
protected static RefKind GetRefKind(ImmutableArray<RefKind> refKindsOpt, int index)
{
return refKindsOpt.IsDefault || refKindsOpt.Length <= index ? RefKind.None : refKindsOpt[index];
}
protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method)
{
}
public override BoundNode VisitBadExpression(BoundBadExpression node)
{
foreach (var child in node.ChildBoundNodes)
{
VisitRvalue(child as BoundExpression);
}
return null;
}
public override BoundNode VisitBadStatement(BoundBadStatement node)
{
foreach (var child in node.ChildBoundNodes)
{
if (child is BoundStatement)
{
VisitStatement(child as BoundStatement);
}
else
{
VisitRvalue(child as BoundExpression);
}
}
return null;
}
// Can be called as part of a bad expression.
public override BoundNode VisitArrayInitialization(BoundArrayInitialization node)
{
foreach (var child in node.Initializers)
{
VisitRvalue(child);
}
return null;
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
var methodGroup = node.Argument as BoundMethodGroup;
if (methodGroup != null)
{
if ((object)node.MethodOpt != null && node.MethodOpt.RequiresInstanceReceiver)
{
EnterRegionIfNeeded(methodGroup);
VisitRvalue(methodGroup.ReceiverOpt);
LeaveRegionIfNeeded(methodGroup);
}
else if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc)
{
VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false);
}
}
else
{
VisitRvalue(node.Argument);
}
return null;
}
public override BoundNode VisitTypeExpression(BoundTypeExpression node)
{
return null;
}
public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node)
{
// If we're seeing a node of this kind, then we failed to resolve the member access
// as either a type or a property/field/event/local/parameter. In such cases,
// the second interpretation applies so just visit the node for that.
return this.Visit(node.Data.ValueExpression);
}
public override BoundNode VisitLiteral(BoundLiteral node)
{
SplitIfBooleanConstant(node);
return null;
}
protected void SplitIfBooleanConstant(BoundExpression node)
{
if (node.ConstantValue is { IsBoolean: true, BooleanValue: bool booleanValue })
{
var unreachable = UnreachableState();
Split();
if (booleanValue)
{
StateWhenFalse = unreachable;
}
else
{
StateWhenTrue = unreachable;
}
}
}
public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node)
{
return null;
}
public override BoundNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node)
{
return null;
}
public override BoundNode VisitModuleVersionId(BoundModuleVersionId node)
{
return null;
}
public override BoundNode VisitModuleVersionIdString(BoundModuleVersionIdString node)
{
return null;
}
public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node)
{
return null;
}
public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node)
{
return null;
}
public override BoundNode VisitConversion(BoundConversion node)
{
if (node.ConversionKind == ConversionKind.MethodGroup)
{
if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && node.SymbolOpt.RequiresInstanceReceiver))
{
BoundExpression receiver = ((BoundMethodGroup)node.Operand).ReceiverOpt;
// A method group's "implicit this" is only used for instance methods.
EnterRegionIfNeeded(node.Operand);
VisitRvalue(receiver);
LeaveRegionIfNeeded(node.Operand);
}
else if (node.SymbolOpt?.OriginalDefinition is LocalFunctionSymbol localFunc)
{
VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false);
}
}
else
{
Visit(node.Operand);
}
return null;
}
public override BoundNode VisitIfStatement(BoundIfStatement node)
{
// 5.3.3.5 If statements
VisitCondition(node.Condition);
TLocalState trueState = StateWhenTrue;
TLocalState falseState = StateWhenFalse;
SetState(trueState);
VisitStatement(node.Consequence);
trueState = this.State;
SetState(falseState);
if (node.AlternativeOpt != null)
{
VisitStatement(node.AlternativeOpt);
}
Join(ref this.State, ref trueState);
return null;
}
public override BoundNode VisitTryStatement(BoundTryStatement node)
{
var oldPending = SavePending(); // we do not allow branches into a try statement
var initialState = this.State.Clone();
// use this state to resolve all the branches introduced and internal to try/catch
var pendingBeforeTry = SavePending();
VisitTryBlockWithAnyTransferFunction(node.TryBlock, node, ref initialState);
var finallyState = initialState.Clone();
var endState = this.State;
foreach (var catchBlock in node.CatchBlocks)
{
SetState(initialState.Clone());
VisitCatchBlockWithAnyTransferFunction(catchBlock, ref finallyState);
Join(ref endState, ref this.State);
}
// Give a chance to branches internal to try/catch to resolve.
// Carry forward unresolved branches.
RestorePending(pendingBeforeTry);
// NOTE: At this point all branches that are internal to try or catch blocks have been resolved.
// However we have not yet restored the oldPending branches. Therefore all the branches
// that are currently pending must have been introduced in try/catch and do not terminate inside those blocks.
//
// With exception of YieldReturn, these branches logically go through finally, if such present,
// so we must Union/Intersect finally state as appropriate
if (node.FinallyBlockOpt != null)
{
// branches from the finally block, while illegal, should still not be considered
// to execute the finally block before occurring. Also, we do not handle branches
// *into* the finally block.
SetState(finallyState);
// capture tryAndCatchPending before going into finally
// we will need pending branches as they were before finally later
var tryAndCatchPending = SavePending();
var stateMovedUpInFinally = ReachableBottomState();
VisitFinallyBlockWithAnyTransferFunction(node.FinallyBlockOpt, ref stateMovedUpInFinally);
foreach (var pend in tryAndCatchPending.PendingBranches)
{
if (pend.Branch == null)
{
continue; // a tracked exception
}
if (pend.Branch.Kind != BoundKind.YieldReturnStatement)
{
updatePendingBranchState(ref pend.State, ref stateMovedUpInFinally);
if (pend.IsConditionalState)
{
updatePendingBranchState(ref pend.StateWhenTrue, ref stateMovedUpInFinally);
updatePendingBranchState(ref pend.StateWhenFalse, ref stateMovedUpInFinally);
}
}
}
RestorePending(tryAndCatchPending);
Meet(ref endState, ref this.State);
if (_nonMonotonicTransfer)
{
Join(ref endState, ref stateMovedUpInFinally);
}
}
SetState(endState);
RestorePending(oldPending);
return null;
void updatePendingBranchState(ref TLocalState stateToUpdate, ref TLocalState stateMovedUpInFinally)
{
Meet(ref stateToUpdate, ref this.State);
if (_nonMonotonicTransfer)
{
Join(ref stateToUpdate, ref stateMovedUpInFinally);
}
}
}
protected Optional<TLocalState> NonMonotonicState;
/// <summary>
/// Join state from other try block, potentially in a nested method.
/// </summary>
protected virtual void JoinTryBlockState(ref TLocalState self, ref TLocalState other)
{
Join(ref self, ref other);
}
private void VisitTryBlockWithAnyTransferFunction(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState)
{
if (_nonMonotonicTransfer)
{
Optional<TLocalState> oldTryState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitTryBlock(tryBlock, node, ref tryState);
var tempTryStateValue = NonMonotonicState.Value;
Join(ref tryState, ref tempTryStateValue);
if (oldTryState.HasValue)
{
var oldTryStateValue = oldTryState.Value;
JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue);
oldTryState = oldTryStateValue;
}
NonMonotonicState = oldTryState;
}
else
{
VisitTryBlock(tryBlock, node, ref tryState);
}
}
protected virtual void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState)
{
VisitStatement(tryBlock);
}
private void VisitCatchBlockWithAnyTransferFunction(BoundCatchBlock catchBlock, ref TLocalState finallyState)
{
if (_nonMonotonicTransfer)
{
Optional<TLocalState> oldTryState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitCatchBlock(catchBlock, ref finallyState);
var tempTryStateValue = NonMonotonicState.Value;
Join(ref finallyState, ref tempTryStateValue);
if (oldTryState.HasValue)
{
var oldTryStateValue = oldTryState.Value;
JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue);
oldTryState = oldTryStateValue;
}
NonMonotonicState = oldTryState;
}
else
{
VisitCatchBlock(catchBlock, ref finallyState);
}
}
protected virtual void VisitCatchBlock(BoundCatchBlock catchBlock, ref TLocalState finallyState)
{
if (catchBlock.ExceptionSourceOpt != null)
{
VisitLvalue(catchBlock.ExceptionSourceOpt);
}
if (catchBlock.ExceptionFilterPrologueOpt is { })
{
VisitStatementList(catchBlock.ExceptionFilterPrologueOpt);
}
if (catchBlock.ExceptionFilterOpt != null)
{
VisitCondition(catchBlock.ExceptionFilterOpt);
SetState(StateWhenTrue);
}
VisitStatement(catchBlock.Body);
}
private void VisitFinallyBlockWithAnyTransferFunction(BoundStatement finallyBlock, ref TLocalState stateMovedUp)
{
if (_nonMonotonicTransfer)
{
Optional<TLocalState> oldTryState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitFinallyBlock(finallyBlock, ref stateMovedUp);
var tempTryStateValue = NonMonotonicState.Value;
Join(ref stateMovedUp, ref tempTryStateValue);
if (oldTryState.HasValue)
{
var oldTryStateValue = oldTryState.Value;
JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue);
oldTryState = oldTryStateValue;
}
NonMonotonicState = oldTryState;
}
else
{
VisitFinallyBlock(finallyBlock, ref stateMovedUp);
}
}
protected virtual void VisitFinallyBlock(BoundStatement finallyBlock, ref TLocalState stateMovedUp)
{
VisitStatement(finallyBlock); // this should generate no pending branches
}
public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node)
{
return VisitBlock(node.FinallyBlock);
}
public override BoundNode VisitReturnStatement(BoundReturnStatement node)
{
var result = VisitReturnStatementNoAdjust(node);
PendingBranches.Add(new PendingBranch(node, this.State, label: null));
SetUnreachable();
return result;
}
protected virtual BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node)
{
VisitRvalue(node.ExpressionOpt, isKnownToBeAnLvalue: node.RefKind != RefKind.None);
// byref return is also a potential write
if (node.RefKind != RefKind.None)
{
WriteArgument(node.ExpressionOpt, node.RefKind, method: null);
}
return null;
}
public override BoundNode VisitThisReference(BoundThisReference node)
{
return null;
}
public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node)
{
return null;
}
public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node)
{
return null;
}
public override BoundNode VisitParameter(BoundParameter node)
{
return null;
}
protected virtual void VisitLvalueParameter(BoundParameter node)
{
}
public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node)
{
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor);
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
public override BoundNode VisitNewT(BoundNewT node)
{
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node)
{
VisitRvalue(node.InitializerExpressionOpt);
return null;
}
// represents anything that occurs at the invocation of the property setter
protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null)
{
VisitReceiverAfterCall(receiver, setter);
}
// returns false if expression is not a property access
// or if the property has a backing field
// and accessed in a corresponding constructor
private bool RegularPropertyAccess(BoundExpression expr)
{
if (expr.Kind != BoundKind.PropertyAccess)
{
return false;
}
return !Binder.AccessingAutoPropertyFromConstructor((BoundPropertyAccess)expr, _symbol);
}
public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node)
{
// TODO: should events be handled specially too?
if (RegularPropertyAccess(node.Left))
{
var left = (BoundPropertyAccess)node.Left;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var method = GetWriteMethod(property);
VisitReceiverBeforeCall(left.ReceiverOpt, method);
VisitRvalue(node.Right);
PropertySetter(node, left.ReceiverOpt, method, node.Right);
return null;
}
}
VisitLvalue(node.Left);
VisitRvalue(node.Right, isKnownToBeAnLvalue: node.IsRef);
// byref assignment is also a potential write
if (node.IsRef)
{
// Assume that BadExpression is a ref location to avoid
// cascading diagnostics
var refKind = node.Left.Kind == BoundKind.BadExpression
? RefKind.Ref
: node.Left.GetRefKind();
WriteArgument(node.Right, refKind, method: null);
}
return null;
}
public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node)
{
VisitLvalue(node.Left);
VisitRvalue(node.Right);
return null;
}
public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node)
{
// OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
VisitCompoundAssignmentTarget(node);
VisitRvalue(node.Right);
AfterRightHasBeenVisited(node);
return null;
}
protected void VisitCompoundAssignmentTarget(BoundCompoundAssignmentOperator node)
{
// TODO: should events be handled specially too?
if (RegularPropertyAccess(node.Left))
{
var left = (BoundPropertyAccess)node.Left;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var readMethod = GetReadMethod(property);
Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)GetWriteMethod(property));
VisitReceiverBeforeCall(left.ReceiverOpt, readMethod);
VisitReceiverAfterCall(left.ReceiverOpt, readMethod);
return;
}
}
VisitRvalue(node.Left, isKnownToBeAnLvalue: true);
}
protected void AfterRightHasBeenVisited(BoundCompoundAssignmentOperator node)
{
if (RegularPropertyAccess(node.Left))
{
var left = (BoundPropertyAccess)node.Left;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var writeMethod = GetWriteMethod(property);
PropertySetter(node, left.ReceiverOpt, writeMethod);
VisitReceiverAfterCall(left.ReceiverOpt, writeMethod);
return;
}
}
}
public override BoundNode VisitFieldAccess(BoundFieldAccess node)
{
VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol);
SplitIfBooleanConstant(node);
return null;
}
private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol)
{
bool asLvalue = (object)fieldSymbol != null &&
(fieldSymbol.IsFixedSizeBuffer ||
!fieldSymbol.IsStatic &&
fieldSymbol.ContainingType.TypeKind == TypeKind.Struct &&
receiverOpt != null &&
receiverOpt.Kind != BoundKind.TypeExpression &&
(object)receiverOpt.Type != null &&
!receiverOpt.Type.IsPrimitiveRecursiveStruct());
if (asLvalue)
{
VisitLvalue(receiverOpt);
}
else
{
VisitRvalue(receiverOpt);
}
}
public override BoundNode VisitFieldInfo(BoundFieldInfo node)
{
return null;
}
public override BoundNode VisitMethodInfo(BoundMethodInfo node)
{
return null;
}
public override BoundNode VisitPropertyAccess(BoundPropertyAccess node)
{
var property = node.PropertySymbol;
if (Binder.AccessingAutoPropertyFromConstructor(node, _symbol))
{
var backingField = (property as SourcePropertySymbolBase)?.BackingField;
if (backingField != null)
{
VisitFieldAccessInternal(node.ReceiverOpt, backingField);
return null;
}
}
var method = GetReadMethod(property);
VisitReceiverBeforeCall(node.ReceiverOpt, method);
VisitReceiverAfterCall(node.ReceiverOpt, method);
return null;
// TODO: In an expression such as
// M().Prop = G();
// Exceptions thrown from M() occur before those from G(), but exceptions from the property accessor
// occur after both. The precise abstract flow pass does not yet currently have this quite right.
// Probably what is needed is a VisitPropertyAccessInternal(BoundPropertyAccess node, bool read)
// which should assume that the receiver will have been handled by the caller. This can be invoked
// twice for read/write operations such as
// M().Prop += 1
// or at the appropriate place in the sequence for read or write operations.
// Do events require any special handling too?
}
public override BoundNode VisitEventAccess(BoundEventAccess node)
{
VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField);
return null;
}
public override BoundNode VisitRangeVariable(BoundRangeVariable node)
{
return null;
}
public override BoundNode VisitQueryClause(BoundQueryClause node)
{
VisitRvalue(node.UnoptimizedForm ?? node.Value);
return null;
}
private BoundNode VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node)
{
foreach (var v in node.LocalDeclarations)
{
Visit(v);
}
return null;
}
public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node)
{
return VisitMultipleLocalDeclarationsBase(node);
}
public override BoundNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node)
{
if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null)
{
PendingBranches.Add(new PendingBranch(node, this.State, null));
}
return VisitMultipleLocalDeclarationsBase(node);
}
public override BoundNode VisitWhileStatement(BoundWhileStatement node)
{
// while (node.Condition) { node.Body; node.ContinueLabel: } node.BreakLabel:
LoopHead(node);
VisitCondition(node.Condition);
TLocalState bodyState = StateWhenTrue;
TLocalState breakState = StateWhenFalse;
SetState(bodyState);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
return null;
}
public override BoundNode VisitWithExpression(BoundWithExpression node)
{
VisitRvalue(node.Receiver);
VisitObjectOrCollectionInitializerExpression(node.InitializerExpression.Initializers);
return null;
}
public override BoundNode VisitArrayAccess(BoundArrayAccess node)
{
VisitRvalue(node.Expression);
foreach (var i in node.Indices)
{
VisitRvalue(i);
}
return null;
}
public override BoundNode VisitBinaryOperator(BoundBinaryOperator node)
{
if (node.OperatorKind.IsLogical())
{
Debug.Assert(!node.OperatorKind.IsUserDefined());
VisitBinaryLogicalOperatorChildren(node);
}
else
{
VisitBinaryOperatorChildren(node);
}
return null;
}
public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node)
{
VisitBinaryLogicalOperatorChildren(node);
return null;
}
private void VisitBinaryLogicalOperatorChildren(BoundExpression node)
{
// Do not blow the stack due to a deep recursion on the left.
var stack = ArrayBuilder<BoundExpression>.GetInstance();
BoundExpression binary;
BoundExpression child = node;
while (true)
{
var childKind = child.Kind;
if (childKind == BoundKind.BinaryOperator)
{
var binOp = (BoundBinaryOperator)child;
if (!binOp.OperatorKind.IsLogical())
{
break;
}
Debug.Assert(!binOp.OperatorKind.IsUserDefined());
binary = child;
child = binOp.Left;
}
else if (childKind == BoundKind.UserDefinedConditionalLogicalOperator)
{
binary = child;
child = ((BoundUserDefinedConditionalLogicalOperator)binary).Left;
}
else
{
break;
}
stack.Push(binary);
}
Debug.Assert(stack.Count > 0);
VisitCondition(child);
while (true)
{
binary = stack.Pop();
BinaryOperatorKind kind;
BoundExpression right;
switch (binary.Kind)
{
case BoundKind.BinaryOperator:
var binOp = (BoundBinaryOperator)binary;
kind = binOp.OperatorKind;
right = binOp.Right;
break;
case BoundKind.UserDefinedConditionalLogicalOperator:
var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary;
kind = udBinOp.OperatorKind;
right = udBinOp.Right;
break;
default:
throw ExceptionUtilities.UnexpectedValue(binary.Kind);
}
var op = kind.Operator();
var isAnd = op == BinaryOperatorKind.And;
var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool;
Debug.Assert(isAnd || op == BinaryOperatorKind.Or);
var leftTrue = this.StateWhenTrue;
var leftFalse = this.StateWhenFalse;
SetState(isAnd ? leftTrue : leftFalse);
AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse);
if (stack.Count == 0)
{
break;
}
AdjustConditionalState(binary);
}
Debug.Assert((object)binary == node);
stack.Free();
}
protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse)
{
Visit(right); // First part of VisitCondition
AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse);
}
protected void AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse)
{
AdjustConditionalState(right); // Second part of VisitCondition
if (!isBool)
{
this.Unsplit();
this.Split();
}
var resultTrue = this.StateWhenTrue;
var resultFalse = this.StateWhenFalse;
if (isAnd)
{
Join(ref resultFalse, ref leftFalse);
}
else
{
Join(ref resultTrue, ref leftTrue);
}
SetConditionalState(resultTrue, resultFalse);
if (!isBool)
{
this.Unsplit();
}
}
private void VisitBinaryOperatorChildren(BoundBinaryOperator node)
{
// It is common in machine-generated code for there to be deep recursion on the left side of a binary
// operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left
// hand side. To mitigate the risk of stack overflow we use an explicit stack.
//
// Of course we must ensure that we visit the left hand side before the right hand side.
var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance();
BoundBinaryOperator binary = node;
do
{
stack.Push(binary);
binary = binary.Left as BoundBinaryOperator;
}
while (binary != null && !binary.OperatorKind.IsLogical());
VisitBinaryOperatorChildren(stack);
stack.Free();
}
#nullable enable
protected virtual void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack)
{
var binary = stack.Pop();
// Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left
// For simplicity, we just special case it here.
// For example, `a?.b(out x) == true` has a conditional access on the left of the operator,
// but `expr == a?.b(out x) == true` has a conditional access on the right of the operator
if (VisitPossibleConditionalAccess(binary.Left, out var stateWhenNotNull)
&& canLearnFromOperator(binary)
&& isKnownNullOrNotNull(binary.Right))
{
if (_nonMonotonicTransfer)
{
// In this very specific scenario, we need to do extra work to track unassignments for region analysis.
// See `AbstractFlowPass.VisitCatchBlockWithAnyTransferFunction` for a similar scenario in catch blocks.
Optional<TLocalState> oldState = NonMonotonicState;
NonMonotonicState = ReachableBottomState();
VisitRvalue(binary.Right);
var tempStateValue = NonMonotonicState.Value;
Join(ref stateWhenNotNull, ref tempStateValue);
if (oldState.HasValue)
{
var oldStateValue = oldState.Value;
Join(ref oldStateValue, ref tempStateValue);
oldState = oldStateValue;
}
NonMonotonicState = oldState;
}
else
{
VisitRvalue(binary.Right);
Meet(ref stateWhenNotNull, ref State);
}
var isNullConstant = binary.Right.ConstantValue?.IsNull == true;
SetConditionalState(isNullConstant == isEquals(binary)
? (State, stateWhenNotNull)
: (stateWhenNotNull, State));
if (stack.Count == 0)
{
return;
}
binary = stack.Pop();
}
while (true)
{
if (!canLearnFromOperator(binary)
|| !learnFromOperator(binary))
{
Unsplit();
Visit(binary.Right);
}
if (stack.Count == 0)
{
break;
}
binary = stack.Pop();
}
static bool canLearnFromOperator(BoundBinaryOperator binary)
{
var kind = binary.OperatorKind;
return kind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual
&& (!kind.IsUserDefined() || kind.IsLifted());
}
static bool isKnownNullOrNotNull(BoundExpression expr)
{
return expr.ConstantValue is object
|| (expr is BoundConversion { ConversionKind: ConversionKind.ExplicitNullable or ConversionKind.ImplicitNullable } conv
&& conv.Operand.Type!.IsNonNullableValueType());
}
static bool isEquals(BoundBinaryOperator binary)
=> binary.OperatorKind.Operator() == BinaryOperatorKind.Equal;
// Returns true if `binary.Right` was visited by the call.
bool learnFromOperator(BoundBinaryOperator binary)
{
// `true == a?.b(out x)`
if (isKnownNullOrNotNull(binary.Left) && TryVisitConditionalAccess(binary.Right, out var stateWhenNotNull))
{
var isNullConstant = binary.Left.ConstantValue?.IsNull == true;
SetConditionalState(isNullConstant == isEquals(binary)
? (State, stateWhenNotNull)
: (stateWhenNotNull, State));
return true;
}
// `a && b(out x) == true`
else if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant)
{
var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone());
Unsplit();
Visit(binary.Right);
SetConditionalState(isEquals(binary) == rightConstant.BooleanValue
? (stateWhenTrue, stateWhenFalse)
: (stateWhenFalse, stateWhenTrue));
return true;
}
// `true == a && b(out x)`
else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant)
{
Unsplit();
Visit(binary.Right);
if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue)
{
SetConditionalState(StateWhenFalse, StateWhenTrue);
}
return true;
}
return false;
}
}
#nullable disable
public override BoundNode VisitUnaryOperator(BoundUnaryOperator node)
{
if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation)
{
// We have a special case for the ! unary operator, which can operate in a boolean context (5.3.3.26)
VisitCondition(node.Operand);
// it inverts the sense of assignedWhenTrue and assignedWhenFalse.
SetConditionalState(StateWhenFalse, StateWhenTrue);
}
else
{
VisitRvalue(node.Operand);
}
return null;
}
public override BoundNode VisitRangeExpression(BoundRangeExpression node)
{
if (node.LeftOperandOpt != null)
{
VisitRvalue(node.LeftOperandOpt);
}
if (node.RightOperandOpt != null)
{
VisitRvalue(node.RightOperandOpt);
}
return null;
}
public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
VisitRvalue(node.Expression);
PendingBranches.Add(new PendingBranch(node, this.State, null));
return null;
}
public override BoundNode VisitIncrementOperator(BoundIncrementOperator node)
{
// TODO: should we also specially handle events?
if (RegularPropertyAccess(node.Operand))
{
var left = (BoundPropertyAccess)node.Operand;
var property = left.PropertySymbol;
if (property.RefKind == RefKind.None)
{
var readMethod = GetReadMethod(property);
var writeMethod = GetWriteMethod(property);
Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod);
VisitReceiverBeforeCall(left.ReceiverOpt, readMethod);
VisitReceiverAfterCall(left.ReceiverOpt, readMethod);
PropertySetter(node, left.ReceiverOpt, writeMethod); // followed by a write
return null;
}
}
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitArrayCreation(BoundArrayCreation node)
{
foreach (var expr in node.Bounds)
{
VisitRvalue(expr);
}
if (node.InitializerOpt != null)
{
VisitArrayInitializationInternal(node, node.InitializerOpt);
}
return null;
}
private void VisitArrayInitializationInternal(BoundArrayCreation arrayCreation, BoundArrayInitialization node)
{
foreach (var child in node.Initializers)
{
if (child.Kind == BoundKind.ArrayInitialization)
{
VisitArrayInitializationInternal(arrayCreation, (BoundArrayInitialization)child);
}
else
{
VisitRvalue(child);
}
}
}
public override BoundNode VisitForStatement(BoundForStatement node)
{
if (node.Initializer != null)
{
VisitStatement(node.Initializer);
}
LoopHead(node);
TLocalState bodyState, breakState;
if (node.Condition != null)
{
VisitCondition(node.Condition);
bodyState = this.StateWhenTrue;
breakState = this.StateWhenFalse;
}
else
{
bodyState = this.State;
breakState = UnreachableState();
}
SetState(bodyState);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
if (node.Increment != null)
{
VisitStatement(node.Increment);
}
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
return null;
}
public override BoundNode VisitForEachStatement(BoundForEachStatement node)
{
// foreach [await] ( var v in node.Expression ) { node.Body; node.ContinueLabel: } node.BreakLabel:
VisitForEachExpression(node);
var breakState = this.State.Clone();
LoopHead(node);
VisitForEachIterationVariables(node);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
if (AwaitUsingAndForeachAddsPendingBranch && ((CommonForEachStatementSyntax)node.Syntax).AwaitKeyword != default)
{
PendingBranches.Add(new PendingBranch(node, this.State, null));
}
return null;
}
protected virtual void VisitForEachExpression(BoundForEachStatement node)
{
VisitRvalue(node.Expression);
}
public virtual void VisitForEachIterationVariables(BoundForEachStatement node)
{
}
public override BoundNode VisitAsOperator(BoundAsOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitIsOperator(BoundIsOperator node)
{
if (VisitPossibleConditionalAccess(node.Operand, out var stateWhenNotNull))
{
Debug.Assert(!IsConditionalState);
SetConditionalState(stateWhenNotNull, State);
}
else
{
// `(a && b.M(out x)) is bool` should discard conditional state from LHS
Unsplit();
}
return null;
}
public override BoundNode VisitMethodGroup(BoundMethodGroup node)
{
if (node.ReceiverOpt != null)
{
// An explicit or implicit receiver, for example in an expression such as (x.Goo is Action, or Goo is Action), is considered to be read.
VisitRvalue(node.ReceiverOpt);
}
return null;
}
#nullable enable
public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node)
{
if (IsConstantNull(node.LeftOperand))
{
VisitRvalue(node.LeftOperand);
Visit(node.RightOperand);
}
else
{
TLocalState savedState;
if (VisitPossibleConditionalAccess(node.LeftOperand, out var stateWhenNotNull))
{
Debug.Assert(!IsConditionalState);
savedState = stateWhenNotNull;
}
else
{
Unsplit();
savedState = State.Clone();
}
if (node.LeftOperand.ConstantValue != null)
{
SetUnreachable();
}
Visit(node.RightOperand);
if (IsConditionalState)
{
Join(ref StateWhenTrue, ref savedState);
Join(ref StateWhenFalse, ref savedState);
}
else
{
Join(ref this.State, ref savedState);
}
}
return null;
}
/// <summary>
/// Visits a node only if it is a conditional access.
/// Returns 'true' if and only if the node was visited.
/// </summary>
private bool TryVisitConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull)
{
var access = node switch
{
BoundConditionalAccess ca => ca,
BoundConversion { Conversion: Conversion conversion, Operand: BoundConditionalAccess ca } when CanPropagateStateWhenNotNull(conversion) => ca,
_ => null
};
if (access is not null)
{
EnterRegionIfNeeded(access);
Unsplit();
VisitConditionalAccess(access, out stateWhenNotNull);
Debug.Assert(!IsConditionalState);
LeaveRegionIfNeeded(access);
return true;
}
stateWhenNotNull = default;
return false;
}
/// <summary>
/// "State when not null" can only propagate out of a conditional access if
/// it is not subject to a user-defined conversion whose parameter is not of a non-nullable value type.
/// </summary>
protected static bool CanPropagateStateWhenNotNull(Conversion conversion)
{
if (!conversion.IsValid)
{
return false;
}
if (!conversion.IsUserDefined)
{
return true;
}
var method = conversion.Method;
Debug.Assert(method is object);
Debug.Assert(method.ParameterCount is 1);
var param = method.Parameters[0];
return param.Type.IsNonNullableValueType();
}
/// <summary>
/// Unconditionally visits an expression.
/// If the expression has "state when not null" after visiting,
/// the method returns 'true' and writes the state to <paramref name="stateWhenNotNull" />.
/// </summary>
private bool VisitPossibleConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull)
{
if (TryVisitConditionalAccess(node, out stateWhenNotNull))
{
return true;
}
else
{
Visit(node);
return false;
}
}
private void VisitConditionalAccess(BoundConditionalAccess node, out TLocalState stateWhenNotNull)
{
// The receiver may also be a conditional access.
// `(a?.b(x = 1))?.c(y = 1)`
if (VisitPossibleConditionalAccess(node.Receiver, out var receiverStateWhenNotNull))
{
stateWhenNotNull = receiverStateWhenNotNull;
}
else
{
Unsplit();
stateWhenNotNull = this.State.Clone();
}
if (node.Receiver.ConstantValue != null && !IsConstantNull(node.Receiver))
{
// Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`.
// We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`.
// Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State
// and includes the "after subsequent conditional accesses" in stateWhenNotNull
if (VisitPossibleConditionalAccess(node.AccessExpression, out var firstAccessStateWhenNotNull))
{
stateWhenNotNull = firstAccessStateWhenNotNull;
}
else
{
Unsplit();
stateWhenNotNull = this.State.Clone();
}
}
else
{
var savedState = this.State.Clone();
if (IsConstantNull(node.Receiver))
{
SetUnreachable();
}
else
{
SetState(stateWhenNotNull);
}
// We want to preserve stateWhenNotNull from accesses in the same "chain":
// a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y)
// but not accesses in nested expressions:
// a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y)
BoundExpression expr = node.AccessExpression;
while (expr is BoundConditionalAccess innerCondAccess)
{
Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion));
// we assume that non-conditional accesses can never contain conditional accesses from the same "chain".
// that is, we never have to dig through non-conditional accesses to find and handle conditional accesses.
VisitRvalue(innerCondAccess.Receiver);
expr = innerCondAccess.AccessExpression;
// The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated.
// e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull.
Join(ref savedState, ref State);
}
Debug.Assert(expr is BoundExpression);
VisitRvalue(expr);
stateWhenNotNull = State;
State = savedState;
Join(ref State, ref stateWhenNotNull);
}
}
public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node)
{
VisitConditionalAccess(node, stateWhenNotNull: out _);
return null;
}
#nullable disable
public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node)
{
VisitRvalue(node.Receiver);
var savedState = this.State.Clone();
VisitRvalue(node.WhenNotNull);
Join(ref this.State, ref savedState);
if (node.WhenNullOpt != null)
{
savedState = this.State.Clone();
VisitRvalue(node.WhenNullOpt);
Join(ref this.State, ref savedState);
}
return null;
}
public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node)
{
return null;
}
public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node)
{
var savedState = this.State.Clone();
VisitRvalue(node.ValueTypeReceiver);
Join(ref this.State, ref savedState);
savedState = this.State.Clone();
VisitRvalue(node.ReferenceTypeReceiver);
Join(ref this.State, ref savedState);
return null;
}
public override BoundNode VisitSequence(BoundSequence node)
{
var sideEffects = node.SideEffects;
if (!sideEffects.IsEmpty)
{
foreach (var se in sideEffects)
{
VisitRvalue(se);
}
}
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitSequencePoint(BoundSequencePoint node)
{
if (node.StatementOpt != null)
{
VisitStatement(node.StatementOpt);
}
return null;
}
public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node)
{
if (node.StatementOpt != null)
{
VisitStatement(node.StatementOpt);
}
return null;
}
public override BoundNode VisitStatementList(BoundStatementList node)
{
return VisitStatementListWorker(node);
}
private BoundNode VisitStatementListWorker(BoundStatementList node)
{
foreach (var statement in node.Statements)
{
VisitStatement(statement);
}
return null;
}
public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node)
{
return VisitStatementListWorker(node);
}
public override BoundNode VisitUnboundLambda(UnboundLambda node)
{
// The presence of this node suggests an error was detected in an earlier phase.
return VisitLambda(node.BindForErrorRecovery());
}
public override BoundNode VisitBreakStatement(BoundBreakStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, node.Label));
SetUnreachable();
return null;
}
public override BoundNode VisitContinueStatement(BoundContinueStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, node.Label));
SetUnreachable();
return null;
}
public override BoundNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node)
{
return VisitConditionalOperatorCore(node, isByRef: false, node.Condition, node.Consequence, node.Alternative);
}
public override BoundNode VisitConditionalOperator(BoundConditionalOperator node)
{
return VisitConditionalOperatorCore(node, node.IsRef, node.Condition, node.Consequence, node.Alternative);
}
#nullable enable
protected virtual BoundNode? VisitConditionalOperatorCore(
BoundExpression node,
bool isByRef,
BoundExpression condition,
BoundExpression consequence,
BoundExpression alternative)
{
VisitCondition(condition);
var consequenceState = this.StateWhenTrue;
var alternativeState = this.StateWhenFalse;
if (IsConstantTrue(condition))
{
VisitConditionalOperand(alternativeState, alternative, isByRef);
VisitConditionalOperand(consequenceState, consequence, isByRef);
}
else if (IsConstantFalse(condition))
{
VisitConditionalOperand(consequenceState, consequence, isByRef);
VisitConditionalOperand(alternativeState, alternative, isByRef);
}
else
{
// at this point, the state is conditional after a conditional expression if:
// 1. the state is conditional after the consequence, or
// 2. the state is conditional after the alternative
VisitConditionalOperand(consequenceState, consequence, isByRef);
var conditionalAfterConsequence = IsConditionalState;
var (afterConsequenceWhenTrue, afterConsequenceWhenFalse) = conditionalAfterConsequence ? (StateWhenTrue, StateWhenFalse) : (State, State);
VisitConditionalOperand(alternativeState, alternative, isByRef);
if (!conditionalAfterConsequence && !IsConditionalState)
{
// simplify in the common case
Join(ref this.State, ref afterConsequenceWhenTrue);
}
else
{
Split();
Join(ref this.StateWhenTrue, ref afterConsequenceWhenTrue);
Join(ref this.StateWhenFalse, ref afterConsequenceWhenFalse);
}
}
return null;
}
#nullable disable
private void VisitConditionalOperand(TLocalState state, BoundExpression operand, bool isByRef)
{
SetState(state);
if (isByRef)
{
VisitLvalue(operand);
// exposing ref is a potential write
WriteArgument(operand, RefKind.Ref, method: null);
}
else
{
Visit(operand);
}
}
public override BoundNode VisitBaseReference(BoundBaseReference node)
{
return null;
}
public override BoundNode VisitDoStatement(BoundDoStatement node)
{
// do { statements; node.ContinueLabel: } while (node.Condition) node.BreakLabel:
LoopHead(node);
VisitStatement(node.Body);
ResolveContinues(node.ContinueLabel);
VisitCondition(node.Condition);
TLocalState breakState = this.StateWhenFalse;
SetState(this.StateWhenTrue);
LoopTail(node);
ResolveBreaks(breakState, node.BreakLabel);
return null;
}
public override BoundNode VisitGotoStatement(BoundGotoStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, node.Label));
SetUnreachable();
return null;
}
protected void VisitLabel(LabelSymbol label, BoundStatement node)
{
node.AssertIsLabeledStatementWithLabel(label);
ResolveBranches(label, node);
var state = LabelState(label);
Join(ref this.State, ref state);
_labels[label] = this.State.Clone();
_labelsSeen.Add(node);
}
protected virtual void VisitLabel(BoundLabeledStatement node)
{
VisitLabel(node.Label, node);
}
public override BoundNode VisitLabelStatement(BoundLabelStatement node)
{
VisitLabel(node.Label, node);
return null;
}
public override BoundNode VisitLabeledStatement(BoundLabeledStatement node)
{
VisitLabel(node);
VisitStatement(node.Body);
return null;
}
public override BoundNode VisitLockStatement(BoundLockStatement node)
{
VisitRvalue(node.Argument);
VisitStatement(node.Body);
return null;
}
public override BoundNode VisitNoOpStatement(BoundNoOpStatement node)
{
return null;
}
public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node)
{
return null;
}
public override BoundNode VisitUsingStatement(BoundUsingStatement node)
{
if (node.ExpressionOpt != null)
{
VisitRvalue(node.ExpressionOpt);
}
if (node.DeclarationsOpt != null)
{
VisitStatement(node.DeclarationsOpt);
}
VisitStatement(node.Body);
if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null)
{
PendingBranches.Add(new PendingBranch(node, this.State, null));
}
return null;
}
public abstract bool AwaitUsingAndForeachAddsPendingBranch { get; }
public override BoundNode VisitFixedStatement(BoundFixedStatement node)
{
VisitStatement(node.Declarations);
VisitStatement(node.Body);
return null;
}
public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitThrowStatement(BoundThrowStatement node)
{
BoundExpression expr = node.ExpressionOpt;
VisitRvalue(expr);
SetUnreachable();
return null;
}
public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node)
{
Debug.Assert(!this.IsConditionalState);
PendingBranches.Add(new PendingBranch(node, this.State, null));
SetUnreachable();
return null;
}
public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node)
{
VisitRvalue(node.Expression);
PendingBranches.Add(new PendingBranch(node, this.State, null));
return null;
}
public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node)
{
return null;
}
public override BoundNode VisitDefaultExpression(BoundDefaultExpression node)
{
return null;
}
public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node)
{
VisitTypeExpression(node.SourceType);
return null;
}
public override BoundNode VisitNameOfOperator(BoundNameOfOperator node)
{
var savedState = this.State;
SetState(UnreachableState());
Visit(node.Argument);
SetState(savedState);
return null;
}
public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node)
{
VisitAddressOfOperand(node.Operand, shouldReadOperand: false);
return null;
}
protected void VisitAddressOfOperand(BoundExpression operand, bool shouldReadOperand)
{
if (shouldReadOperand)
{
this.VisitRvalue(operand);
}
else
{
this.VisitLvalue(operand);
}
this.WriteArgument(operand, RefKind.Out, null); //Out because we know it will definitely be assigned.
}
public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node)
{
VisitRvalue(node.Expression);
VisitRvalue(node.Index);
return null;
}
public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node)
{
return null;
}
private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node)
{
VisitRvalue(node.Count);
if (node.InitializerOpt != null && !node.InitializerOpt.Initializers.IsDefault)
{
foreach (var element in node.InitializerOpt.Initializers)
{
VisitRvalue(element);
}
}
return null;
}
public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node)
{
return VisitStackAllocArrayCreationBase(node);
}
public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node)
{
return VisitStackAllocArrayCreationBase(node);
}
public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node)
{
// visit arguments as r-values
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.Constructor);
return null;
}
public override BoundNode VisitArrayLength(BoundArrayLength node)
{
VisitRvalue(node.Expression);
return null;
}
public override BoundNode VisitConditionalGoto(BoundConditionalGoto node)
{
VisitCondition(node.Condition);
Debug.Assert(this.IsConditionalState);
if (node.JumpIfTrue)
{
PendingBranches.Add(new PendingBranch(node, this.StateWhenTrue, node.Label));
this.SetState(this.StateWhenFalse);
}
else
{
PendingBranches.Add(new PendingBranch(node, this.StateWhenFalse, node.Label));
this.SetState(this.StateWhenTrue);
}
return null;
}
public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node)
{
return VisitObjectOrCollectionInitializerExpression(node.Initializers);
}
public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node)
{
return VisitObjectOrCollectionInitializerExpression(node.Initializers);
}
private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray<BoundExpression> initializers)
{
foreach (var initializer in initializers)
{
VisitRvalue(initializer);
}
return null;
}
public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node)
{
var arguments = node.Arguments;
if (!arguments.IsDefaultOrEmpty)
{
MethodSymbol method = null;
if (node.MemberSymbol?.Kind == SymbolKind.Property)
{
var property = (PropertySymbol)node.MemberSymbol;
method = GetReadMethod(property);
}
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method);
}
return null;
}
public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node)
{
return null;
}
public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node)
{
if (node.AddMethod.CallsAreOmitted(node.SyntaxTree))
{
// If the underlying add method is a partial method without a definition, or is a conditional method
// whose condition is not true, then the call has no effect and it is ignored for the purposes of
// flow analysis.
TLocalState savedState = savedState = this.State.Clone();
SetUnreachable();
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod);
this.State = savedState;
}
else
{
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod);
}
return null;
}
public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node)
{
VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), method: null);
return null;
}
public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node)
{
return null;
}
public override BoundNode VisitFieldEqualsValue(BoundFieldEqualsValue node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitParameterEqualsValue(BoundParameterEqualsValue node)
{
VisitRvalue(node.Value);
return null;
}
public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node)
{
return null;
}
public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node)
{
return null;
}
public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node)
{
return null;
}
public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node)
{
throw ExceptionUtilities.Unreachable;
}
public sealed override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node)
{
throw ExceptionUtilities.Unreachable;
}
public override BoundNode VisitDiscardExpression(BoundDiscardExpression node)
{
return null;
}
private static MethodSymbol GetReadMethod(PropertySymbol property) =>
property.GetOwnOrInheritedGetMethod() ?? property.SetMethod;
private static MethodSymbol GetWriteMethod(PropertySymbol property) =>
property.GetOwnOrInheritedSetMethod() ?? property.GetMethod;
public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node)
{
Visit(node.Initializer);
VisitMethodBodies(node.BlockBody, node.ExpressionBody);
return null;
}
public override BoundNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node)
{
VisitMethodBodies(node.BlockBody, node.ExpressionBody);
return null;
}
public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node)
{
TLocalState leftState;
if (RegularPropertyAccess(node.LeftOperand) &&
(BoundPropertyAccess)node.LeftOperand is var left &&
left.PropertySymbol is var property &&
property.RefKind == RefKind.None)
{
var readMethod = property.GetOwnOrInheritedGetMethod();
VisitReceiverBeforeCall(left.ReceiverOpt, readMethod);
VisitReceiverAfterCall(left.ReceiverOpt, readMethod);
var savedState = this.State.Clone();
AdjustStateForNullCoalescingAssignmentNonNullCase(node);
leftState = this.State.Clone();
SetState(savedState);
VisitAssignmentOfNullCoalescingAssignment(node, left);
}
else
{
VisitRvalue(node.LeftOperand, isKnownToBeAnLvalue: true);
var savedState = this.State.Clone();
AdjustStateForNullCoalescingAssignmentNonNullCase(node);
leftState = this.State.Clone();
SetState(savedState);
VisitAssignmentOfNullCoalescingAssignment(node, propertyAccessOpt: null);
}
Join(ref this.State, ref leftState);
return null;
}
public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node)
{
VisitRvalue(node.Operand);
return null;
}
public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node)
{
Visit(node.InvokedExpression);
VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature);
return null;
}
public override BoundNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node)
{
// This is not encountered in correct programs, but can be seen if the function pointer was
// unable to be converted and the semantic model is used to query for information.
Visit(node.Operand);
return null;
}
/// <summary>
/// This visitor represents just the assignment part of the null coalescing assignment
/// operator.
/// </summary>
protected virtual void VisitAssignmentOfNullCoalescingAssignment(
BoundNullCoalescingAssignmentOperator node,
BoundPropertyAccess propertyAccessOpt)
{
VisitRvalue(node.RightOperand);
if (propertyAccessOpt != null)
{
var symbol = propertyAccessOpt.PropertySymbol;
var writeMethod = symbol.GetOwnOrInheritedSetMethod();
PropertySetter(node, propertyAccessOpt.ReceiverOpt, writeMethod);
}
}
public override BoundNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node)
{
return null;
}
public override BoundNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node)
{
return null;
}
public override BoundNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node)
{
return null;
}
/// <summary>
/// This visitor represents just the non-assignment part of the null coalescing assignment
/// operator (when the left operand is non-null).
/// </summary>
protected virtual void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node)
{
}
private void VisitMethodBodies(BoundBlock blockBody, BoundBlock expressionBody)
{
if (blockBody == null)
{
Visit(expressionBody);
return;
}
else if (expressionBody == null)
{
Visit(blockBody);
return;
}
// In error cases we have two bodies. These are two unrelated pieces of code,
// they are not executed one after another. As we don't really know which one the developer
// intended to use, we need to visit both. We are going to pretend that there is
// an unconditional fork in execution and then we are converging after each body is executed.
// For example, if only one body assigns an out parameter, then after visiting both bodies
// we should consider that parameter is not definitely assigned.
// Note, that today this code is not executed for regular definite assignment analysis. It is
// only executed for region analysis.
TLocalState initialState = this.State.Clone();
Visit(blockBody);
TLocalState afterBlock = this.State;
SetState(initialState);
Visit(expressionBody);
Join(ref this.State, ref afterBlock);
}
#endregion visitors
}
/// <summary>
/// The possible places that we are processing when there is a region.
/// </summary>
/// <remarks>
/// This should be nested inside <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}"/> but is not due to https://github.com/dotnet/roslyn/issues/36992 .
/// </remarks>
internal enum RegionPlace { Before, Inside, After };
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Classification/IRemoteSemanticClassificationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
internal interface IRemoteSemanticClassificationService
{
ValueTask<SerializableClassifiedSpans> GetSemanticClassificationsAsync(
PinnedSolutionInfo solutionInfo, DocumentId documentId, TextSpan span, CancellationToken cancellationToken);
}
/// <summary>
/// For space efficiency, we encode classified spans as triples of ints in one large array. The
/// first int is the index of classification type in <see cref="ClassificationTypes"/>, and the
/// second and third ints encode the span.
/// </summary>
[DataContract]
internal sealed class SerializableClassifiedSpans
{
[DataMember(Order = 0)]
public List<string>? ClassificationTypes;
[DataMember(Order = 1)]
public List<int>? ClassificationTriples;
internal static SerializableClassifiedSpans Dehydrate(ImmutableArray<ClassifiedSpan> classifiedSpans)
{
using var _ = PooledDictionary<string, int>.GetInstance(out var classificationTypeToId);
return Dehydrate(classifiedSpans, classificationTypeToId);
}
private static SerializableClassifiedSpans Dehydrate(ImmutableArray<ClassifiedSpan> classifiedSpans, Dictionary<string, int> classificationTypeToId)
{
var classificationTypes = new List<string>();
var classificationTriples = new List<int>(capacity: classifiedSpans.Length * 3);
foreach (var classifiedSpan in classifiedSpans)
{
var type = classifiedSpan.ClassificationType;
if (!classificationTypeToId.TryGetValue(type, out var id))
{
id = classificationTypes.Count;
classificationTypes.Add(type);
classificationTypeToId.Add(type, id);
}
var textSpan = classifiedSpan.TextSpan;
classificationTriples.Add(id);
classificationTriples.Add(textSpan.Start);
classificationTriples.Add(textSpan.Length);
}
return new SerializableClassifiedSpans
{
ClassificationTypes = classificationTypes,
ClassificationTriples = classificationTriples,
};
}
internal void Rehydrate(ArrayBuilder<ClassifiedSpan> classifiedSpans)
{
Contract.ThrowIfNull(ClassificationTypes);
Contract.ThrowIfNull(ClassificationTriples);
for (var i = 0; i < ClassificationTriples.Count; i += 3)
{
classifiedSpans.Add(new ClassifiedSpan(
ClassificationTypes[ClassificationTriples[i + 0]],
new TextSpan(
ClassificationTriples[i + 1],
ClassificationTriples[i + 2])));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
internal interface IRemoteSemanticClassificationService
{
ValueTask<SerializableClassifiedSpans> GetSemanticClassificationsAsync(
PinnedSolutionInfo solutionInfo, DocumentId documentId, TextSpan span, CancellationToken cancellationToken);
}
/// <summary>
/// For space efficiency, we encode classified spans as triples of ints in one large array. The
/// first int is the index of classification type in <see cref="ClassificationTypes"/>, and the
/// second and third ints encode the span.
/// </summary>
[DataContract]
internal sealed class SerializableClassifiedSpans
{
[DataMember(Order = 0)]
public List<string>? ClassificationTypes;
[DataMember(Order = 1)]
public List<int>? ClassificationTriples;
internal static SerializableClassifiedSpans Dehydrate(ImmutableArray<ClassifiedSpan> classifiedSpans)
{
using var _ = PooledDictionary<string, int>.GetInstance(out var classificationTypeToId);
return Dehydrate(classifiedSpans, classificationTypeToId);
}
private static SerializableClassifiedSpans Dehydrate(ImmutableArray<ClassifiedSpan> classifiedSpans, Dictionary<string, int> classificationTypeToId)
{
var classificationTypes = new List<string>();
var classificationTriples = new List<int>(capacity: classifiedSpans.Length * 3);
foreach (var classifiedSpan in classifiedSpans)
{
var type = classifiedSpan.ClassificationType;
if (!classificationTypeToId.TryGetValue(type, out var id))
{
id = classificationTypes.Count;
classificationTypes.Add(type);
classificationTypeToId.Add(type, id);
}
var textSpan = classifiedSpan.TextSpan;
classificationTriples.Add(id);
classificationTriples.Add(textSpan.Start);
classificationTriples.Add(textSpan.Length);
}
return new SerializableClassifiedSpans
{
ClassificationTypes = classificationTypes,
ClassificationTriples = classificationTriples,
};
}
internal void Rehydrate(ArrayBuilder<ClassifiedSpan> classifiedSpans)
{
Contract.ThrowIfNull(ClassificationTypes);
Contract.ThrowIfNull(ClassificationTriples);
for (var i = 0; i < ClassificationTriples.Count; i += 3)
{
classifiedSpans.Add(new ClassifiedSpan(
ClassificationTypes[ClassificationTriples[i + 0]],
new TextSpan(
ClassificationTriples[i + 1],
ClassificationTriples[i + 2])));
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Lsif/Generator/Graph/ResultSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph
{
/// <summary>
/// Represents a single ResultSet for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#result-set for further details.
/// </summary>
internal sealed class ResultSet : Vertex
{
public ResultSet(IdFactory idFactory)
: base(label: "resultSet", idFactory)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph
{
/// <summary>
/// Represents a single ResultSet for serialization. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#result-set for further details.
/// </summary>
internal sealed class ResultSet : Vertex
{
public ResultSet(IdFactory idFactory)
: base(label: "resultSet", idFactory)
{
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.IndexOf.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.IndexOf.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of the List class.
/// </summary>
public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T>
{
#region Helpers
internal delegate int IndexOfDelegate(SegmentedList<T> list, T value);
public enum IndexOfMethod
{
IndexOf_T,
IndexOf_T_int,
IndexOf_T_int_int,
LastIndexOf_T,
LastIndexOf_T_int,
LastIndexOf_T_int_int,
};
private IndexOfDelegate IndexOfDelegateFromType(IndexOfMethod methodType)
{
switch (methodType)
{
case (IndexOfMethod.IndexOf_T):
return ((SegmentedList<T> list, T value) => { return list.IndexOf(value); });
case (IndexOfMethod.IndexOf_T_int):
return ((SegmentedList<T> list, T value) => { return list.IndexOf(value, 0); });
case (IndexOfMethod.IndexOf_T_int_int):
return ((SegmentedList<T> list, T value) => { return list.IndexOf(value, 0, list.Count); });
case (IndexOfMethod.LastIndexOf_T):
return ((SegmentedList<T> list, T value) => { return list.LastIndexOf(value); });
case (IndexOfMethod.LastIndexOf_T_int):
return ((SegmentedList<T> list, T value) => { return list.LastIndexOf(value, list.Count - 1); });
case (IndexOfMethod.LastIndexOf_T_int_int):
return ((SegmentedList<T> list, T value) => { return list.LastIndexOf(value, list.Count - 1, list.Count); });
default:
throw new Exception("Invalid IndexOfMethod");
}
}
/// <summary>
/// MemberData for a Theory to test the IndexOf methods for List. To avoid high code reuse of tests for the 6 IndexOf
/// methods in List, delegates are used to cover the basic behavioral cases shared by all IndexOf methods. A bool
/// is used to specify the ordering (front-to-back or back-to-front (e.g. LastIndexOf)) that the IndexOf method
/// searches in.
/// </summary>
public static IEnumerable<object[]> IndexOfTestData()
{
foreach (object[] sizes in ValidCollectionSizes())
{
int count = (int)sizes[0];
yield return new object[] { IndexOfMethod.IndexOf_T, count, true };
yield return new object[] { IndexOfMethod.LastIndexOf_T, count, false };
if (count > 0) // 0 is an invalid index for IndexOf when the count is 0.
{
yield return new object[] { IndexOfMethod.IndexOf_T_int, count, true };
yield return new object[] { IndexOfMethod.LastIndexOf_T_int, count, false };
yield return new object[] { IndexOfMethod.IndexOf_T_int_int, count, true };
yield return new object[] { IndexOfMethod.LastIndexOf_T_int_int, count, false };
}
}
}
#endregion
#region IndexOf
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_NoDuplicates(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
_ = frontToBackOrder;
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> expectedList = list.ToSegmentedList();
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
Assert.All(Enumerable.Range(0, count), i =>
{
Assert.Equal(i, IndexOf(list, expectedList[i]));
});
}
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_NonExistingValues(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
_ = frontToBackOrder;
SegmentedList<T> list = GenericListFactory(count);
IEnumerable<T> nonexistentValues = CreateEnumerable(EnumerableType.List, list, count: count, numberOfMatchingElements: 0, numberOfDuplicateElements: 0);
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
Assert.All(nonexistentValues, nonexistentValue =>
{
Assert.Equal(-1, IndexOf(list, nonexistentValue));
});
}
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_DefaultValue(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
_ = frontToBackOrder;
T? defaultValue = default;
SegmentedList<T?> list = GenericListFactory(count)!;
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
while (list.Remove(defaultValue))
count--;
list.Add(defaultValue);
Assert.Equal(count, IndexOf(list!, defaultValue!));
}
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_OrderIsCorrect(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> withoutDuplicates = list.ToSegmentedList();
list.AddRange(list);
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
Assert.All(Enumerable.Range(0, count), i =>
{
if (frontToBackOrder)
Assert.Equal(i, IndexOf(list, withoutDuplicates[i]));
else
Assert.Equal(count + i, IndexOf(list, withoutDuplicates[i]));
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IndexOf_int_OrderIsCorrectWithManyDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> withoutDuplicates = list.ToSegmentedList();
list.AddRange(list);
list.AddRange(list);
list.AddRange(list);
Assert.All(Enumerable.Range(0, count), i =>
{
Assert.All(Enumerable.Range(0, 4), j =>
{
int expectedIndex = (j * count) + i;
Assert.Equal(expectedIndex, list.IndexOf(withoutDuplicates[i], (count * j)));
Assert.Equal(expectedIndex, list.IndexOf(withoutDuplicates[i], (count * j), count));
});
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void LastIndexOf_int_OrderIsCorrectWithManyDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> withoutDuplicates = list.ToSegmentedList();
list.AddRange(list);
list.AddRange(list);
list.AddRange(list);
Assert.All(Enumerable.Range(0, count), i =>
{
Assert.All(Enumerable.Range(0, 4), j =>
{
int expectedIndex = (j * count) + i;
Assert.Equal(expectedIndex, list.LastIndexOf(withoutDuplicates[i], (count * (j + 1)) - 1));
Assert.Equal(expectedIndex, list.LastIndexOf(withoutDuplicates[i], (count * (j + 1)) - 1, count));
});
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IndexOf_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count + 1)); //"Expect ArgumentOutOfRangeException for index greater than length of list.."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count + 10)); //"Expect ArgumentOutOfRangeException for index greater than length of list.."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, -1)); //"Expect ArgumentOutOfRangeException for negative index."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, int.MinValue)); //"Expect ArgumentOutOfRangeException for negative index."
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IndexOf_int_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count, 1)); //"ArgumentOutOfRangeException expected on index larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count + 1, 1)); //"ArgumentOutOfRangeException expected on index larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, 0, count + 1)); //"ArgumentOutOfRangeException expected on count larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count / 2, count / 2 + 2)); //"ArgumentOutOfRangeException expected.."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, 0, count + 1)); //"ArgumentOutOfRangeException expected on count larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, 0, -1)); //"ArgumentOutOfRangeException expected on negative count."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, -1, 1)); //"ArgumentOutOfRangeException expected on negative index."
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void LastIndexOf_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count)); //"ArgumentOutOfRangeException expected."
if (count == 0) // IndexOf with a 0 count List is special cased to return -1.
Assert.Equal(-1, list.LastIndexOf(element, -1));
else
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, -1));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void LastIndexOf_int_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
if (count > 0)
{
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, 0, count + 1)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count / 2, count / 2 + 2)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, 0, count + 1)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, 0, -1)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, -1, count)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, -1, 1)); //"Expected ArgumentOutOfRangeException." Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count, 0)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count, 1)); //"Expected ArgumentOutOfRangeException."
}
else // IndexOf with a 0 count List is special cased to return -1.
{
Assert.Equal(-1, list.LastIndexOf(element, 0, count + 1));
Assert.Equal(-1, list.LastIndexOf(element, count / 2, count / 2 + 2));
Assert.Equal(-1, list.LastIndexOf(element, 0, count + 1));
Assert.Equal(-1, list.LastIndexOf(element, 0, -1));
Assert.Equal(-1, list.LastIndexOf(element, -1, count));
Assert.Equal(-1, list.LastIndexOf(element, -1, 1));
Assert.Equal(-1, list.LastIndexOf(element, count, 0));
Assert.Equal(-1, list.LastIndexOf(element, count, 1));
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.IndexOf.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of the List class.
/// </summary>
public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T>
{
#region Helpers
internal delegate int IndexOfDelegate(SegmentedList<T> list, T value);
public enum IndexOfMethod
{
IndexOf_T,
IndexOf_T_int,
IndexOf_T_int_int,
LastIndexOf_T,
LastIndexOf_T_int,
LastIndexOf_T_int_int,
};
private IndexOfDelegate IndexOfDelegateFromType(IndexOfMethod methodType)
{
switch (methodType)
{
case (IndexOfMethod.IndexOf_T):
return ((SegmentedList<T> list, T value) => { return list.IndexOf(value); });
case (IndexOfMethod.IndexOf_T_int):
return ((SegmentedList<T> list, T value) => { return list.IndexOf(value, 0); });
case (IndexOfMethod.IndexOf_T_int_int):
return ((SegmentedList<T> list, T value) => { return list.IndexOf(value, 0, list.Count); });
case (IndexOfMethod.LastIndexOf_T):
return ((SegmentedList<T> list, T value) => { return list.LastIndexOf(value); });
case (IndexOfMethod.LastIndexOf_T_int):
return ((SegmentedList<T> list, T value) => { return list.LastIndexOf(value, list.Count - 1); });
case (IndexOfMethod.LastIndexOf_T_int_int):
return ((SegmentedList<T> list, T value) => { return list.LastIndexOf(value, list.Count - 1, list.Count); });
default:
throw new Exception("Invalid IndexOfMethod");
}
}
/// <summary>
/// MemberData for a Theory to test the IndexOf methods for List. To avoid high code reuse of tests for the 6 IndexOf
/// methods in List, delegates are used to cover the basic behavioral cases shared by all IndexOf methods. A bool
/// is used to specify the ordering (front-to-back or back-to-front (e.g. LastIndexOf)) that the IndexOf method
/// searches in.
/// </summary>
public static IEnumerable<object[]> IndexOfTestData()
{
foreach (object[] sizes in ValidCollectionSizes())
{
int count = (int)sizes[0];
yield return new object[] { IndexOfMethod.IndexOf_T, count, true };
yield return new object[] { IndexOfMethod.LastIndexOf_T, count, false };
if (count > 0) // 0 is an invalid index for IndexOf when the count is 0.
{
yield return new object[] { IndexOfMethod.IndexOf_T_int, count, true };
yield return new object[] { IndexOfMethod.LastIndexOf_T_int, count, false };
yield return new object[] { IndexOfMethod.IndexOf_T_int_int, count, true };
yield return new object[] { IndexOfMethod.LastIndexOf_T_int_int, count, false };
}
}
}
#endregion
#region IndexOf
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_NoDuplicates(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
_ = frontToBackOrder;
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> expectedList = list.ToSegmentedList();
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
Assert.All(Enumerable.Range(0, count), i =>
{
Assert.Equal(i, IndexOf(list, expectedList[i]));
});
}
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_NonExistingValues(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
_ = frontToBackOrder;
SegmentedList<T> list = GenericListFactory(count);
IEnumerable<T> nonexistentValues = CreateEnumerable(EnumerableType.List, list, count: count, numberOfMatchingElements: 0, numberOfDuplicateElements: 0);
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
Assert.All(nonexistentValues, nonexistentValue =>
{
Assert.Equal(-1, IndexOf(list, nonexistentValue));
});
}
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_DefaultValue(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
_ = frontToBackOrder;
T? defaultValue = default;
SegmentedList<T?> list = GenericListFactory(count)!;
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
while (list.Remove(defaultValue))
count--;
list.Add(defaultValue);
Assert.Equal(count, IndexOf(list!, defaultValue!));
}
[Theory]
[MemberData(nameof(IndexOfTestData))]
public void IndexOf_OrderIsCorrect(IndexOfMethod indexOfMethod, int count, bool frontToBackOrder)
{
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> withoutDuplicates = list.ToSegmentedList();
list.AddRange(list);
IndexOfDelegate IndexOf = IndexOfDelegateFromType(indexOfMethod);
Assert.All(Enumerable.Range(0, count), i =>
{
if (frontToBackOrder)
Assert.Equal(i, IndexOf(list, withoutDuplicates[i]));
else
Assert.Equal(count + i, IndexOf(list, withoutDuplicates[i]));
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IndexOf_int_OrderIsCorrectWithManyDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> withoutDuplicates = list.ToSegmentedList();
list.AddRange(list);
list.AddRange(list);
list.AddRange(list);
Assert.All(Enumerable.Range(0, count), i =>
{
Assert.All(Enumerable.Range(0, 4), j =>
{
int expectedIndex = (j * count) + i;
Assert.Equal(expectedIndex, list.IndexOf(withoutDuplicates[i], (count * j)));
Assert.Equal(expectedIndex, list.IndexOf(withoutDuplicates[i], (count * j), count));
});
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void LastIndexOf_int_OrderIsCorrectWithManyDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
SegmentedList<T> withoutDuplicates = list.ToSegmentedList();
list.AddRange(list);
list.AddRange(list);
list.AddRange(list);
Assert.All(Enumerable.Range(0, count), i =>
{
Assert.All(Enumerable.Range(0, 4), j =>
{
int expectedIndex = (j * count) + i;
Assert.Equal(expectedIndex, list.LastIndexOf(withoutDuplicates[i], (count * (j + 1)) - 1));
Assert.Equal(expectedIndex, list.LastIndexOf(withoutDuplicates[i], (count * (j + 1)) - 1, count));
});
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IndexOf_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count + 1)); //"Expect ArgumentOutOfRangeException for index greater than length of list.."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count + 10)); //"Expect ArgumentOutOfRangeException for index greater than length of list.."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, -1)); //"Expect ArgumentOutOfRangeException for negative index."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, int.MinValue)); //"Expect ArgumentOutOfRangeException for negative index."
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IndexOf_int_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count, 1)); //"ArgumentOutOfRangeException expected on index larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count + 1, 1)); //"ArgumentOutOfRangeException expected on index larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, 0, count + 1)); //"ArgumentOutOfRangeException expected on count larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, count / 2, count / 2 + 2)); //"ArgumentOutOfRangeException expected.."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, 0, count + 1)); //"ArgumentOutOfRangeException expected on count larger than array."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, 0, -1)); //"ArgumentOutOfRangeException expected on negative count."
Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(element, -1, 1)); //"ArgumentOutOfRangeException expected on negative index."
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void LastIndexOf_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count)); //"ArgumentOutOfRangeException expected."
if (count == 0) // IndexOf with a 0 count List is special cased to return -1.
Assert.Equal(-1, list.LastIndexOf(element, -1));
else
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, -1));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void LastIndexOf_int_int_OutOfRangeExceptions(int count)
{
SegmentedList<T> list = GenericListFactory(count);
T element = CreateT(234);
if (count > 0)
{
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, 0, count + 1)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count / 2, count / 2 + 2)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, 0, count + 1)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, 0, -1)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, -1, count)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, -1, 1)); //"Expected ArgumentOutOfRangeException." Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count, 0)); //"Expected ArgumentOutOfRangeException."
Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(element, count, 1)); //"Expected ArgumentOutOfRangeException."
}
else // IndexOf with a 0 count List is special cased to return -1.
{
Assert.Equal(-1, list.LastIndexOf(element, 0, count + 1));
Assert.Equal(-1, list.LastIndexOf(element, count / 2, count / 2 + 2));
Assert.Equal(-1, list.LastIndexOf(element, 0, count + 1));
Assert.Equal(-1, list.LastIndexOf(element, 0, -1));
Assert.Equal(-1, list.LastIndexOf(element, -1, count));
Assert.Equal(-1, list.LastIndexOf(element, -1, 1));
Assert.Equal(-1, list.LastIndexOf(element, count, 0));
Assert.Equal(-1, list.LastIndexOf(element, count, 1));
}
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandlerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FixInterpolatedVerbatimString
{
[UseExportProvider]
public class FixInterpolatedVerbatimStringCommandHandlerTests
{
private static TestWorkspace CreateTestWorkspace(string inputMarkup)
{
var workspace = TestWorkspace.CreateCSharp(inputMarkup);
var document = workspace.Documents.Single();
var view = document.GetTextView();
view.SetSelection(document.SelectedSpans.Single().ToSnapshotSpan(view.TextBuffer.CurrentSnapshot));
return workspace;
}
private static (string quoteCharSnapshotText, int quoteCharCaretPosition) TypeQuoteChar(TestWorkspace workspace)
{
var view = workspace.Documents.Single().GetTextView();
var commandHandler = workspace.ExportProvider.GetCommandHandler<FixInterpolatedVerbatimStringCommandHandler>(nameof(FixInterpolatedVerbatimStringCommandHandler));
string quoteCharSnapshotText = null;
int quoteCharCaretPosition = default;
commandHandler.ExecuteCommand(new TypeCharCommandArgs(view, view.TextBuffer, '"'),
() =>
{
var editorOperations = workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(view);
editorOperations.InsertText("\"");
quoteCharSnapshotText = view.TextBuffer.CurrentSnapshot.GetText();
quoteCharCaretPosition = view.Caret.Position.BufferPosition.Position;
}, TestCommandExecutionContext.Create());
return (quoteCharSnapshotText, quoteCharCaretPosition);
}
private static void TestHandled(string inputMarkup, string expectedOutputMarkup)
{
using var workspace = CreateTestWorkspace(inputMarkup);
var (quoteCharSnapshotText, quoteCharCaretPosition) = TypeQuoteChar(workspace);
var view = workspace.Documents.Single().GetTextView();
MarkupTestFile.GetSpans(expectedOutputMarkup,
out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans);
Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(expectedSpans.Single().Start, view.Caret.Position.BufferPosition.Position);
var history = workspace.GetService<ITextUndoHistoryRegistry>().GetHistory(view.TextBuffer);
history.Undo(count: 1);
// Ensure that after undo, the ordering fix is undone but the quote remains inserted
Assert.Equal(quoteCharSnapshotText, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(quoteCharCaretPosition, view.Caret.Position.BufferPosition.Position);
}
private static void TestNotHandled(string inputMarkup)
{
using var workspace = CreateTestWorkspace(inputMarkup);
var originalView = workspace.Documents.Single().GetTextView();
var originalSnapshotText = originalView.TextBuffer.CurrentSnapshot.GetText();
var originalCaretPosition = originalView.Caret.Position.BufferPosition.Position;
var (quoteCharSnapshotText, quoteCharCaretPosition) = TypeQuoteChar(workspace);
var view = workspace.Documents.Single().GetTextView();
Assert.Equal(quoteCharSnapshotText, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(quoteCharCaretPosition, view.Caret.Position.BufferPosition.Position);
var history = workspace.GetService<ITextUndoHistoryRegistry>().GetHistory(view.TextBuffer);
history.Undo(count: 1);
// Ensure that after undo, the quote is removed because the command made no changes
Assert.Equal(originalSnapshotText, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(originalCaretPosition, view.Caret.Position.BufferPosition.Position);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestAfterAtSignDollarSign()
{
TestHandled(
@"class C
{
void M()
{
var v = @$[||]
}
}",
@"class C
{
void M()
{
var v = $@""[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingAfterDollarSignAtSign()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $@[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingAfterAtSign()
{
TestNotHandled(
@"class C
{
void M()
{
var v = @[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingAfterDollarSign()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void TestMissingInEmptyFileAfterAtSignDollarSign()
=> TestHandled(@"@$[||]", @"$@""[||]");
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInEmptyFileAfterDollarSign()
=> TestNotHandled(@"$[||]");
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInEmptyFile()
=> TestNotHandled(@"[||]");
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestAfterAtSignDollarSignEndOfFile()
{
TestHandled(
@"class C
{
void M()
{
var v = @$[||]",
@"class C
{
void M()
{
var v = $@""[||]");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInClassDeclaration()
{
TestNotHandled(
@"class C
{
@$[||]
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInComment1()
{
TestNotHandled(
@"class C
{
void M()
{
var v = // @$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInComment2()
{
TestNotHandled(
@"class C
{
void M()
{
var v = /* @$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInString()
{
TestNotHandled(
@"class C
{
void M()
{
var v = ""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInVerbatimString()
{
TestNotHandled(
@"class C
{
void M()
{
var v = @""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInInterpolatedString()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInInterpolatedVerbatimString1()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $@""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInInterpolatedVerbatimString2()
{
TestNotHandled(
@"class C
{
void M()
{
var v = @$""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestTrivia()
{
TestHandled(
@"class C
{
void M()
{
var v = // a
/* b */ @$[||] // c
}
}",
@"class C
{
void M()
{
var v = // a
/* b */ $@""[||] // c
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FixInterpolatedVerbatimString
{
[UseExportProvider]
public class FixInterpolatedVerbatimStringCommandHandlerTests
{
private static TestWorkspace CreateTestWorkspace(string inputMarkup)
{
var workspace = TestWorkspace.CreateCSharp(inputMarkup);
var document = workspace.Documents.Single();
var view = document.GetTextView();
view.SetSelection(document.SelectedSpans.Single().ToSnapshotSpan(view.TextBuffer.CurrentSnapshot));
return workspace;
}
private static (string quoteCharSnapshotText, int quoteCharCaretPosition) TypeQuoteChar(TestWorkspace workspace)
{
var view = workspace.Documents.Single().GetTextView();
var commandHandler = workspace.ExportProvider.GetCommandHandler<FixInterpolatedVerbatimStringCommandHandler>(nameof(FixInterpolatedVerbatimStringCommandHandler));
string quoteCharSnapshotText = null;
int quoteCharCaretPosition = default;
commandHandler.ExecuteCommand(new TypeCharCommandArgs(view, view.TextBuffer, '"'),
() =>
{
var editorOperations = workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(view);
editorOperations.InsertText("\"");
quoteCharSnapshotText = view.TextBuffer.CurrentSnapshot.GetText();
quoteCharCaretPosition = view.Caret.Position.BufferPosition.Position;
}, TestCommandExecutionContext.Create());
return (quoteCharSnapshotText, quoteCharCaretPosition);
}
private static void TestHandled(string inputMarkup, string expectedOutputMarkup)
{
using var workspace = CreateTestWorkspace(inputMarkup);
var (quoteCharSnapshotText, quoteCharCaretPosition) = TypeQuoteChar(workspace);
var view = workspace.Documents.Single().GetTextView();
MarkupTestFile.GetSpans(expectedOutputMarkup,
out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans);
Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(expectedSpans.Single().Start, view.Caret.Position.BufferPosition.Position);
var history = workspace.GetService<ITextUndoHistoryRegistry>().GetHistory(view.TextBuffer);
history.Undo(count: 1);
// Ensure that after undo, the ordering fix is undone but the quote remains inserted
Assert.Equal(quoteCharSnapshotText, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(quoteCharCaretPosition, view.Caret.Position.BufferPosition.Position);
}
private static void TestNotHandled(string inputMarkup)
{
using var workspace = CreateTestWorkspace(inputMarkup);
var originalView = workspace.Documents.Single().GetTextView();
var originalSnapshotText = originalView.TextBuffer.CurrentSnapshot.GetText();
var originalCaretPosition = originalView.Caret.Position.BufferPosition.Position;
var (quoteCharSnapshotText, quoteCharCaretPosition) = TypeQuoteChar(workspace);
var view = workspace.Documents.Single().GetTextView();
Assert.Equal(quoteCharSnapshotText, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(quoteCharCaretPosition, view.Caret.Position.BufferPosition.Position);
var history = workspace.GetService<ITextUndoHistoryRegistry>().GetHistory(view.TextBuffer);
history.Undo(count: 1);
// Ensure that after undo, the quote is removed because the command made no changes
Assert.Equal(originalSnapshotText, view.TextBuffer.CurrentSnapshot.GetText());
Assert.Equal(originalCaretPosition, view.Caret.Position.BufferPosition.Position);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestAfterAtSignDollarSign()
{
TestHandled(
@"class C
{
void M()
{
var v = @$[||]
}
}",
@"class C
{
void M()
{
var v = $@""[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingAfterDollarSignAtSign()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $@[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingAfterAtSign()
{
TestNotHandled(
@"class C
{
void M()
{
var v = @[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingAfterDollarSign()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void TestMissingInEmptyFileAfterAtSignDollarSign()
=> TestHandled(@"@$[||]", @"$@""[||]");
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInEmptyFileAfterDollarSign()
=> TestNotHandled(@"$[||]");
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInEmptyFile()
=> TestNotHandled(@"[||]");
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestAfterAtSignDollarSignEndOfFile()
{
TestHandled(
@"class C
{
void M()
{
var v = @$[||]",
@"class C
{
void M()
{
var v = $@""[||]");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInClassDeclaration()
{
TestNotHandled(
@"class C
{
@$[||]
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInComment1()
{
TestNotHandled(
@"class C
{
void M()
{
var v = // @$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInComment2()
{
TestNotHandled(
@"class C
{
void M()
{
var v = /* @$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInString()
{
TestNotHandled(
@"class C
{
void M()
{
var v = ""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInVerbatimString()
{
TestNotHandled(
@"class C
{
void M()
{
var v = @""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInInterpolatedString()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInInterpolatedVerbatimString1()
{
TestNotHandled(
@"class C
{
void M()
{
var v = $@""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestMissingInInterpolatedVerbatimString2()
{
TestNotHandled(
@"class C
{
void M()
{
var v = @$""@$[||]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)]
public void TestTrivia()
{
TestHandled(
@"class C
{
void M()
{
var v = // a
/* b */ @$[||] // c
}
}",
@"class C
{
void M()
{
var v = // a
/* b */ $@""[||] // c
}
}");
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Rename/ConflictEngine/ConflictResolver.Session.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Rename.ConflictEngine
{
internal static partial class ConflictResolver
{
/// <summary>
/// Helper class to track the state necessary for finding/resolving conflicts in a
/// rename session.
/// </summary>
private class Session
{
// Set of All Locations that will be renamed (does not include non-reference locations that need to be checked for conflicts)
private readonly RenameLocations _renameLocationSet;
// Rename Symbol's Source Location
private readonly Location _renameSymbolDeclarationLocation;
private readonly DocumentId _documentIdOfRenameSymbolDeclaration;
private readonly string _originalText;
private readonly string _replacementText;
private readonly RenameOptionSet _optionSet;
private readonly ImmutableHashSet<ISymbol>? _nonConflictSymbols;
private readonly CancellationToken _cancellationToken;
private readonly RenameAnnotation _renamedSymbolDeclarationAnnotation;
// Contains Strings like Bar -> BarAttribute ; Property Bar -> Bar , get_Bar, set_Bar
private readonly List<string> _possibleNameConflicts;
private readonly HashSet<DocumentId> _documentsIdsToBeCheckedForConflict;
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
private ISet<ConflictLocationInfo> _conflictLocations;
private bool _replacementTextValid;
private List<ProjectId>? _topologicallySortedProjects;
private bool _documentOfRenameSymbolHasBeenRenamed;
public Session(
RenameLocations renameLocationSet,
Location renameSymbolDeclarationLocation,
string replacementText,
ImmutableHashSet<ISymbol>? nonConflictSymbols,
CancellationToken cancellationToken)
{
_renameLocationSet = renameLocationSet;
_renameSymbolDeclarationLocation = renameSymbolDeclarationLocation;
_originalText = renameLocationSet.Symbol.Name;
_replacementText = replacementText;
_optionSet = renameLocationSet.Options;
_nonConflictSymbols = nonConflictSymbols;
_cancellationToken = cancellationToken;
_renamedSymbolDeclarationAnnotation = new RenameAnnotation();
_conflictLocations = SpecializedCollections.EmptySet<ConflictLocationInfo>();
_replacementTextValid = true;
_possibleNameConflicts = new List<string>();
// only process documents which possibly contain the identifiers.
_documentsIdsToBeCheckedForConflict = new HashSet<DocumentId>();
_documentIdOfRenameSymbolDeclaration = renameLocationSet.Solution.GetRequiredDocument(renameSymbolDeclarationLocation.SourceTree!).Id;
_renameAnnotations = new AnnotationTable<RenameAnnotation>(RenameAnnotation.Kind);
}
private struct ConflictLocationInfo
{
// The span of the Node that needs to be complexified
public readonly TextSpan ComplexifiedSpan;
public readonly DocumentId DocumentId;
// The identifier span that needs to be checked for conflict
public readonly TextSpan OriginalIdentifierSpan;
public ConflictLocationInfo(RelatedLocation location)
{
Debug.Assert(location.ComplexifiedTargetSpan.Contains(location.ConflictCheckSpan) || location.Type == RelatedLocationType.UnresolvableConflict);
this.ComplexifiedSpan = location.ComplexifiedTargetSpan;
this.DocumentId = location.DocumentId;
this.OriginalIdentifierSpan = location.ConflictCheckSpan;
}
}
// The method which performs rename, resolves the conflict locations and returns the result of the rename operation
public async Task<MutableConflictResolution> ResolveConflictsAsync()
{
try
{
await FindDocumentsAndPossibleNameConflictsAsync().ConfigureAwait(false);
var baseSolution = _renameLocationSet.Solution;
// Process rename one project at a time to improve caching and reduce syntax tree serialization.
RoslynDebug.Assert(_topologicallySortedProjects != null);
var documentsGroupedByTopologicallySortedProjectId = _documentsIdsToBeCheckedForConflict
.GroupBy(d => d.ProjectId)
.OrderBy(g => _topologicallySortedProjects.IndexOf(g.Key));
_replacementTextValid = IsIdentifierValid_Worker(baseSolution, _replacementText, documentsGroupedByTopologicallySortedProjectId.Select(g => g.Key));
var renamedSpansTracker = new RenamedSpansTracker();
var conflictResolution = new MutableConflictResolution(baseSolution, renamedSpansTracker, _replacementText, _replacementTextValid);
var intermediateSolution = conflictResolution.OldSolution;
foreach (var documentsByProject in documentsGroupedByTopologicallySortedProjectId)
{
var documentIdsThatGetsAnnotatedAndRenamed = new HashSet<DocumentId>(documentsByProject);
using (baseSolution.Services.CacheService?.EnableCaching(documentsByProject.Key))
{
// Rename is going to be in 5 phases.
// 1st phase - Does a simple token replacement
// If the 1st phase results in conflict then we perform then:
// 2nd phase is to expand and simplify only the reference locations with conflicts
// 3rd phase is to expand and simplify all the conflict locations (both reference and non-reference)
// If there are unresolved Conflicts after the 3rd phase then in 4th phase,
// We complexify and resolve locations that were resolvable and for the other locations we perform the normal token replacement like the first the phase.
// If the OptionSet has RenameFile to true, we rename files with the type declaration
for (var phase = 0; phase < 4; phase++)
{
// Step 1:
// The rename process and annotation for the bookkeeping is performed in one-step
// The Process in short is,
// 1. If renaming a token which is no conflict then replace the token and make a map of the oldspan to the newspan
// 2. If we encounter a node that has to be expanded( because there was a conflict in previous phase), we expand it.
// If the node happens to contain a token that needs to be renamed then we annotate it and rename it after expansion else just expand and proceed
// 3. Through the whole process we maintain a map of the oldspan to newspan. In case of expansion & rename, we map the expanded node and the renamed token
conflictResolution.UpdateCurrentSolution(await AnnotateAndRename_WorkerAsync(
baseSolution,
conflictResolution.CurrentSolution,
documentIdsThatGetsAnnotatedAndRenamed,
_renameLocationSet.Locations,
renamedSpansTracker,
_replacementTextValid).ConfigureAwait(false));
// Step 2: Check for conflicts in the renamed solution
var foundResolvableConflicts = await IdentifyConflictsAsync(
documentIdsForConflictResolution: documentIdsThatGetsAnnotatedAndRenamed,
allDocumentIdsInProject: documentsByProject,
projectId: documentsByProject.Key,
conflictResolution: conflictResolution).ConfigureAwait(false);
if (!foundResolvableConflicts || phase == 3)
{
break;
}
if (phase == 0)
{
_conflictLocations = conflictResolution.RelatedLocations
.Where(loc => (documentIdsThatGetsAnnotatedAndRenamed.Contains(loc.DocumentId) && loc.Type == RelatedLocationType.PossiblyResolvableConflict && loc.IsReference))
.Select(loc => new ConflictLocationInfo(loc))
.ToSet();
// If there were no conflicting locations in references, then the first conflict phase has to be skipped.
if (_conflictLocations.Count == 0)
{
phase++;
}
}
if (phase == 1)
{
_conflictLocations = _conflictLocations.Concat(conflictResolution.RelatedLocations
.Where(loc => documentIdsThatGetsAnnotatedAndRenamed.Contains(loc.DocumentId) && loc.Type == RelatedLocationType.PossiblyResolvableConflict)
.Select(loc => new ConflictLocationInfo(loc)))
.ToSet();
}
// Set the documents with conflicts that need to be processed in the next phase.
// Note that we need to get the conflictLocations here since we're going to remove some locations below if phase == 2
documentIdsThatGetsAnnotatedAndRenamed = new HashSet<DocumentId>(_conflictLocations.Select(l => l.DocumentId));
if (phase == 2)
{
// After phase 2, if there are still conflicts then remove the conflict locations from being expanded
var unresolvedLocations = conflictResolution.RelatedLocations
.Where(l => (l.Type & RelatedLocationType.UnresolvedConflict) != 0)
.Select(l => Tuple.Create(l.ComplexifiedTargetSpan, l.DocumentId)).Distinct();
_conflictLocations = _conflictLocations.Where(l => !unresolvedLocations.Any(c => c.Item2 == l.DocumentId && c.Item1.Contains(l.OriginalIdentifierSpan))).ToSet();
}
// Clean up side effects from rename before entering the next phase
conflictResolution.ClearDocuments(documentIdsThatGetsAnnotatedAndRenamed);
}
// Step 3: Simplify the project
conflictResolution.UpdateCurrentSolution(await renamedSpansTracker.SimplifyAsync(conflictResolution.CurrentSolution, documentsByProject, _replacementTextValid, _renameAnnotations, _cancellationToken).ConfigureAwait(false));
intermediateSolution = await conflictResolution.RemoveAllRenameAnnotationsAsync(
intermediateSolution, documentsByProject, _renameAnnotations, _cancellationToken).ConfigureAwait(false);
conflictResolution.UpdateCurrentSolution(intermediateSolution);
}
}
// This rename could break implicit references of this symbol (e.g. rename MoveNext on a collection like type in a
// foreach/for each statement
var renamedSymbolInNewSolution = await GetRenamedSymbolInCurrentSolutionAsync(conflictResolution).ConfigureAwait(false);
if (IsRenameValid(conflictResolution, renamedSymbolInNewSolution))
{
await AddImplicitConflictsAsync(
renamedSymbolInNewSolution,
_renameLocationSet.Symbol,
_renameLocationSet.ImplicitLocations,
await conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration).GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false),
_renameSymbolDeclarationLocation,
renamedSpansTracker.GetAdjustedPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration),
conflictResolution,
_cancellationToken).ConfigureAwait(false);
}
for (var i = 0; i < conflictResolution.RelatedLocations.Count; i++)
{
var relatedLocation = conflictResolution.RelatedLocations[i];
if (relatedLocation.Type == RelatedLocationType.PossiblyResolvableConflict)
conflictResolution.RelatedLocations[i] = relatedLocation.WithType(RelatedLocationType.UnresolvedConflict);
}
#if DEBUG
await DebugVerifyNoErrorsAsync(conflictResolution, _documentsIdsToBeCheckedForConflict).ConfigureAwait(false);
#endif
// Step 5: Rename declaration files
if (_optionSet.RenameFile)
{
var definitionLocations = _renameLocationSet.Symbol.Locations;
var definitionDocuments = definitionLocations
.Select(l => conflictResolution.OldSolution.GetDocument(l.SourceTree))
.Distinct();
if (definitionDocuments.Count() == 1 && _replacementTextValid)
{
// At the moment, only single document renaming is allowed
conflictResolution.RenameDocumentToMatchNewSymbol(definitionDocuments.Single());
}
}
return conflictResolution;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
#if DEBUG
private async Task DebugVerifyNoErrorsAsync(MutableConflictResolution conflictResolution, IEnumerable<DocumentId> documents)
{
var documentIdErrorStateLookup = new Dictionary<DocumentId, bool>();
// we only check for the documentIds we add annotations to, which is a subset of the ones we're going
// to change the syntax in.
foreach (var documentId in documents)
{
// remember if there were issues in the document prior to renaming it.
var originalDoc = conflictResolution.OldSolution.GetRequiredDocument(documentId);
documentIdErrorStateLookup.Add(documentId, await originalDoc.HasAnyErrorsAsync(_cancellationToken).ConfigureAwait(false));
}
// We want to ignore few error message introduced by rename because the user is wantedly doing it.
var ignoreErrorCodes = new List<string>();
ignoreErrorCodes.Add("BC30420"); // BC30420 - Sub Main missing in VB Project
ignoreErrorCodes.Add("CS5001"); // CS5001 - Missing Main in C# Project
// only check if rename thinks it was successful
if (conflictResolution.ReplacementTextValid && conflictResolution.RelatedLocations.All(loc => (loc.Type & RelatedLocationType.UnresolvableConflict) == 0))
{
foreach (var documentId in documents)
{
// only check documents that had no errors before rename (we might have
// fixed them because of rename). Also, don't bother checking if a custom
// callback was provided. The caller might be ok with a rename that introduces
// errors.
if (!documentIdErrorStateLookup[documentId] && _nonConflictSymbols == null)
{
await conflictResolution.CurrentSolution.GetRequiredDocument(documentId).VerifyNoErrorsAsync("Rename introduced errors in error-free code", _cancellationToken, ignoreErrorCodes).ConfigureAwait(false);
}
}
}
}
#endif
/// <summary>
/// Find conflicts in the new solution
/// </summary>
private async Task<bool> IdentifyConflictsAsync(
HashSet<DocumentId> documentIdsForConflictResolution,
IEnumerable<DocumentId> allDocumentIdsInProject,
ProjectId projectId,
MutableConflictResolution conflictResolution)
{
try
{
_documentOfRenameSymbolHasBeenRenamed |= documentIdsForConflictResolution.Contains(_documentIdOfRenameSymbolDeclaration);
// Get the renamed symbol in complexified new solution
var renamedSymbolInNewSolution = await GetRenamedSymbolInCurrentSolutionAsync(conflictResolution).ConfigureAwait(false);
// if the text replacement is invalid, we just did a simple token replacement.
// Therefore we don't need more mapping information and can skip the rest of
// the loop body.
if (!IsRenameValid(conflictResolution, renamedSymbolInNewSolution))
{
foreach (var documentId in documentIdsForConflictResolution)
{
var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(documentId);
var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot);
foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations)
{
if (annotation.IsRenameLocation)
{
conflictResolution.AddRelatedLocation(new RelatedLocation(
annotation.OriginalSpan, documentId, RelatedLocationType.UnresolvedConflict));
}
}
}
return false;
}
var reverseMappedLocations = new Dictionary<Location, Location>();
// If we were giving any non-conflict-symbols then ensure that we know what those symbols are in
// the current project post after our edits so far.
var currentProject = conflictResolution.CurrentSolution.GetRequiredProject(projectId);
var nonConflictSymbols = await GetNonConflictSymbolsAsync(currentProject).ConfigureAwait(false);
foreach (var documentId in documentIdsForConflictResolution)
{
var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(documentId);
var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var baseDocument = conflictResolution.OldSolution.GetRequiredDocument(documentId);
var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);
var baseRoot = await baseDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
SemanticModel? newDocumentSemanticModel = null;
var syntaxFactsService = newDocument.Project.LanguageServices.GetRequiredService<ISyntaxFactsService>();
// Get all tokens that need conflict check
var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot);
var complexifiedLocationSpanForThisDocument =
_conflictLocations
.Where(t => t.DocumentId == documentId)
.Select(t => t.OriginalIdentifierSpan).ToSet();
foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations)
{
var tokenOrNode = syntax;
var conflictAnnotation = annotation;
reverseMappedLocations[tokenOrNode.GetLocation()!] = baseSyntaxTree.GetLocation(conflictAnnotation.OriginalSpan);
var originalLocation = conflictAnnotation.OriginalSpan;
ImmutableArray<ISymbol> newReferencedSymbols = default;
var hasConflict = _renameAnnotations.HasAnnotation(tokenOrNode, RenameInvalidIdentifierAnnotation.Instance);
if (!hasConflict)
{
newDocumentSemanticModel ??= await newDocument.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
newReferencedSymbols = GetSymbolsInNewSolution(newDocument, newDocumentSemanticModel, conflictAnnotation, tokenOrNode);
// The semantic correctness, after rename, for each token of interest in the
// rename context is performed by getting the symbol pointed by each token
// and obtain the Symbol's First Ordered Location's Span-Start and check to
// see if it is the same as before from the base solution. During rename,
// the spans would have been modified and so we need to adjust the old position
// to the new position for which we use the renameSpanTracker, which was tracking
// & mapping the old span -> new span during rename
hasConflict =
!IsConflictFreeChange(newReferencedSymbols, nonConflictSymbols) &&
await CheckForConflictAsync(conflictResolution, renamedSymbolInNewSolution, conflictAnnotation, newReferencedSymbols).ConfigureAwait(false);
if (!hasConflict && !conflictAnnotation.IsInvocationExpression)
hasConflict = LocalVariableConflictPerLanguage((SyntaxToken)tokenOrNode, newDocument, newReferencedSymbols);
}
if (!hasConflict)
{
if (conflictAnnotation.IsRenameLocation)
{
conflictResolution.AddRelatedLocation(
new RelatedLocation(originalLocation,
documentId,
complexifiedLocationSpanForThisDocument.Contains(originalLocation) ? RelatedLocationType.ResolvedReferenceConflict : RelatedLocationType.NoConflict,
isReference: true));
}
else
{
// if a complexified location was not a reference location, then it was a resolved conflict of a non reference location
if (!conflictAnnotation.IsOriginalTextLocation && complexifiedLocationSpanForThisDocument.Contains(originalLocation))
{
conflictResolution.AddRelatedLocation(
new RelatedLocation(originalLocation,
documentId,
RelatedLocationType.ResolvedNonReferenceConflict,
isReference: false));
}
}
}
else
{
var baseToken = baseRoot.FindToken(conflictAnnotation.OriginalSpan.Start, true);
var complexifiedTarget = GetExpansionTargetForLocationPerLanguage(baseToken, baseDocument);
conflictResolution.AddRelatedLocation(new RelatedLocation(
originalLocation,
documentId,
complexifiedTarget != null ? RelatedLocationType.PossiblyResolvableConflict : RelatedLocationType.UnresolvableConflict,
isReference: conflictAnnotation.IsRenameLocation,
complexifiedTargetSpan: complexifiedTarget != null ? complexifiedTarget.Span : default));
}
}
}
// there are more conflicts that cannot be identified by checking if the tokens still reference the same
// symbol. These conflicts are mostly language specific. A good example is a member with the same name
// as the parent (yes I know, this is a simplification).
if (_documentIdOfRenameSymbolDeclaration.ProjectId == projectId)
{
// Calculating declaration conflicts may require location mapping in documents
// that were not otherwise being processed in the current rename phase, so add
// the annotated spans in these documents to reverseMappedLocations.
foreach (var unprocessedDocumentIdWithPotentialDeclarationConflicts in allDocumentIdsInProject.Where(d => !documentIdsForConflictResolution.Contains(d)))
{
var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(unprocessedDocumentIdWithPotentialDeclarationConflicts);
var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var baseDocument = conflictResolution.OldSolution.GetRequiredDocument(unprocessedDocumentIdWithPotentialDeclarationConflicts);
var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);
var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot);
foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations)
{
var tokenOrNode = syntax;
var conflictAnnotation = annotation;
reverseMappedLocations[tokenOrNode.GetLocation()!] = baseSyntaxTree.GetLocation(conflictAnnotation.OriginalSpan);
}
}
var referencedSymbols = _renameLocationSet.ReferencedSymbols;
var renameSymbol = _renameLocationSet.Symbol;
await AddDeclarationConflictsAsync(
renamedSymbolInNewSolution, renameSymbol, referencedSymbols, conflictResolution, reverseMappedLocations, _cancellationToken).ConfigureAwait(false);
}
return conflictResolution.RelatedLocations.Any(r => r.Type == RelatedLocationType.PossiblyResolvableConflict);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<ImmutableHashSet<ISymbol>?> GetNonConflictSymbolsAsync(Project currentProject)
{
if (_nonConflictSymbols == null)
return null;
var compilation = await currentProject.GetRequiredCompilationAsync(_cancellationToken).ConfigureAwait(false);
return ImmutableHashSet.CreateRange(
_nonConflictSymbols.Select(s => s.GetSymbolKey().Resolve(compilation).GetAnySymbol()).WhereNotNull());
}
private bool IsConflictFreeChange(
ImmutableArray<ISymbol> symbols, ImmutableHashSet<ISymbol>? nonConflictSymbols)
{
if (_nonConflictSymbols != null)
{
RoslynDebug.Assert(nonConflictSymbols != null);
foreach (var symbol in symbols)
{
// Reference not points at a symbol in the conflict-free list. This is a conflict-free change.
if (nonConflictSymbols.Contains(symbol))
return true;
}
}
// Just do the default check.
return false;
}
/// <summary>
/// Gets the list of the nodes that were annotated for a conflict check
/// </summary>
private IEnumerable<(SyntaxNodeOrToken syntax, RenameActionAnnotation annotation)> GetNodesOrTokensToCheckForConflicts(
SyntaxNode syntaxRoot)
{
return syntaxRoot.DescendantNodesAndTokens(descendIntoTrivia: true)
.Where(s => _renameAnnotations.HasAnnotations<RenameActionAnnotation>(s))
.Select(s => (s, _renameAnnotations.GetAnnotations<RenameActionAnnotation>(s).Single()));
}
private async Task<bool> CheckForConflictAsync(
MutableConflictResolution conflictResolution,
ISymbol renamedSymbolInNewSolution,
RenameActionAnnotation conflictAnnotation,
ImmutableArray<ISymbol> newReferencedSymbols)
{
try
{
bool hasConflict;
var solution = conflictResolution.CurrentSolution;
if (conflictAnnotation.IsNamespaceDeclarationReference)
{
hasConflict = false;
}
else if (conflictAnnotation.IsMemberGroupReference)
{
if (!conflictAnnotation.RenameDeclarationLocationReferences.Any())
{
hasConflict = false;
}
else
{
// Ensure newReferencedSymbols contains at least one of the original referenced
// symbols, and allow any new symbols to be added to the set of references.
hasConflict = true;
var newLocationTasks = newReferencedSymbols.Select(async symbol => await GetSymbolLocationAsync(solution, symbol, _cancellationToken).ConfigureAwait(false));
var newLocations = (await Task.WhenAll(newLocationTasks).ConfigureAwait(false)).WhereNotNull().Where(loc => loc.IsInSource);
foreach (var originalReference in conflictAnnotation.RenameDeclarationLocationReferences.Where(loc => loc.IsSourceLocation))
{
var adjustedStartPosition = conflictResolution.GetAdjustedTokenStartingPosition(originalReference.TextSpan.Start, originalReference.DocumentId);
if (newLocations.Any(loc => loc.SourceSpan.Start == adjustedStartPosition))
{
hasConflict = false;
break;
}
}
}
}
else if (!conflictAnnotation.IsRenameLocation && conflictAnnotation.IsOriginalTextLocation && conflictAnnotation.RenameDeclarationLocationReferences.Length > 1 && newReferencedSymbols.Length == 1)
{
// an ambiguous situation was resolved through rename in non reference locations
hasConflict = false;
}
else if (newReferencedSymbols.Length != conflictAnnotation.RenameDeclarationLocationReferences.Length)
{
// Don't show conflicts for errors in the old solution that now bind in the new solution.
if (newReferencedSymbols.Length != 0 && conflictAnnotation.RenameDeclarationLocationReferences.Length == 0)
{
hasConflict = false;
}
else
{
hasConflict = true;
}
}
else
{
hasConflict = false;
var symbolIndex = 0;
foreach (var symbol in newReferencedSymbols)
{
if (conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].SymbolLocationsCount != symbol.Locations.Length)
{
hasConflict = true;
break;
}
var newLocation = await GetSymbolLocationAsync(solution, symbol, _cancellationToken).ConfigureAwait(false);
if (newLocation != null && conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].IsSourceLocation)
{
// location was in source before, but not after rename
if (!newLocation.IsInSource)
{
hasConflict = true;
break;
}
var renameDeclarationLocationReference = conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex];
var newAdjustedStartPosition = conflictResolution.GetAdjustedTokenStartingPosition(renameDeclarationLocationReference.TextSpan.Start, renameDeclarationLocationReference.DocumentId);
if (newAdjustedStartPosition != newLocation.SourceSpan.Start)
{
hasConflict = true;
break;
}
if (conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].IsOverriddenFromMetadata)
{
var overridingSymbol = await SymbolFinder.FindSymbolAtPositionAsync(solution.GetRequiredDocument(newLocation.SourceTree), newLocation.SourceSpan.Start, cancellationToken: _cancellationToken).ConfigureAwait(false);
if (overridingSymbol != null && !Equals(renamedSymbolInNewSolution, overridingSymbol))
{
if (!overridingSymbol.IsOverride)
{
hasConflict = true;
break;
}
else
{
var overriddenSymbol = overridingSymbol.GetOverriddenMember();
if (overriddenSymbol == null || !overriddenSymbol.Locations.All(loc => loc.IsInMetadata))
{
hasConflict = true;
break;
}
}
}
}
}
else
{
var newMetadataName = symbol.ToDisplayString(s_metadataSymbolDisplayFormat);
var oldMetadataName = conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].Name;
if (newLocation == null ||
newLocation.IsInSource ||
!HeuristicMetadataNameEquivalenceCheck(
oldMetadataName,
newMetadataName,
_originalText,
_replacementText))
{
hasConflict = true;
break;
}
}
symbolIndex++;
}
}
return hasConflict;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private ImmutableArray<ISymbol> GetSymbolsInNewSolution(Document newDocument, SemanticModel newDocumentSemanticModel, RenameActionAnnotation conflictAnnotation, SyntaxNodeOrToken tokenOrNode)
{
var newReferencedSymbols = RenameUtilities.GetSymbolsTouchingPosition(tokenOrNode.Span.Start, newDocumentSemanticModel, newDocument.Project.Solution.Workspace, _cancellationToken);
if (conflictAnnotation.IsInvocationExpression)
{
if (tokenOrNode.IsNode)
{
var invocationReferencedSymbols = SymbolsForEnclosingInvocationExpressionWorker((SyntaxNode)tokenOrNode!, newDocumentSemanticModel, _cancellationToken);
if (!invocationReferencedSymbols.IsDefault)
newReferencedSymbols = invocationReferencedSymbols;
}
}
// if there are more than one symbol, then remove the alias symbols.
// When using (not declaring) an alias, the alias symbol and the target symbol are returned
// by GetSymbolsTouchingPosition
if (newReferencedSymbols.Length >= 2)
newReferencedSymbols = newReferencedSymbols.WhereAsArray(a => a.Kind != SymbolKind.Alias);
return newReferencedSymbols;
}
private async Task<ISymbol> GetRenamedSymbolInCurrentSolutionAsync(MutableConflictResolution conflictResolution)
{
try
{
// get the renamed symbol in complexified new solution
var start = _documentOfRenameSymbolHasBeenRenamed
? conflictResolution.GetAdjustedTokenStartingPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration)
: _renameSymbolDeclarationLocation.SourceSpan.Start;
var document = conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration);
var newSymbol = await SymbolFinder.FindSymbolAtPositionAsync(document, start, cancellationToken: _cancellationToken).ConfigureAwait(false);
return newSymbol;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// The method determines the set of documents that need to be processed for Rename and also determines
/// the possible set of names that need to be checked for conflicts.
/// </summary>
private async Task FindDocumentsAndPossibleNameConflictsAsync()
{
try
{
var symbol = _renameLocationSet.Symbol;
var solution = _renameLocationSet.Solution;
var dependencyGraph = solution.GetProjectDependencyGraph();
_topologicallySortedProjects = dependencyGraph.GetTopologicallySortedProjects(_cancellationToken).ToList();
var allRenamedDocuments = _renameLocationSet.Locations.Select(loc => loc.Location.SourceTree!).Distinct().Select(solution.GetRequiredDocument);
_documentsIdsToBeCheckedForConflict.AddRange(allRenamedDocuments.Select(d => d.Id));
var documentsFromAffectedProjects = RenameUtilities.GetDocumentsAffectedByRename(symbol, solution, _renameLocationSet.Locations);
foreach (var language in documentsFromAffectedProjects.Select(d => d.Project.Language).Distinct())
{
solution.Workspace.Services.GetLanguageServices(language).GetService<IRenameRewriterLanguageService>()
?.TryAddPossibleNameConflicts(symbol, _replacementText, _possibleNameConflicts);
}
await AddDocumentsWithPotentialConflictsAsync(documentsFromAffectedProjects).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AddDocumentsWithPotentialConflictsAsync(IEnumerable<Document> documents)
{
try
{
foreach (var document in documents)
{
if (_documentsIdsToBeCheckedForConflict.Contains(document.Id))
continue;
if (!document.SupportsSyntaxTree)
continue;
var info = await SyntaxTreeIndex.GetRequiredIndexAsync(document, _cancellationToken).ConfigureAwait(false);
if (info.ProbablyContainsEscapedIdentifier(_originalText))
{
_documentsIdsToBeCheckedForConflict.Add(document.Id);
continue;
}
if (info.ProbablyContainsIdentifier(_replacementText))
{
_documentsIdsToBeCheckedForConflict.Add(document.Id);
continue;
}
foreach (var replacementName in _possibleNameConflicts)
{
if (info.ProbablyContainsIdentifier(replacementName))
{
_documentsIdsToBeCheckedForConflict.Add(document.Id);
break;
}
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
// The rename process and annotation for the bookkeeping is performed in one-step
private async Task<Solution> AnnotateAndRename_WorkerAsync(
Solution originalSolution,
Solution partiallyRenamedSolution,
HashSet<DocumentId> documentIdsToRename,
ISet<RenameLocation> renameLocations,
RenamedSpansTracker renameSpansTracker,
bool replacementTextValid)
{
try
{
foreach (var documentId in documentIdsToRename.ToList())
{
_cancellationToken.ThrowIfCancellationRequested();
var document = originalSolution.GetRequiredDocument(documentId);
var semanticModel = await document.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
var originalSyntaxRoot = await semanticModel.SyntaxTree.GetRootAsync(_cancellationToken).ConfigureAwait(false);
// Get all rename locations for the current document.
var allTextSpansInSingleSourceTree = renameLocations
.Where(l => l.DocumentId == documentId && ShouldIncludeLocation(renameLocations, l))
.ToDictionary(l => l.Location.SourceSpan);
// All textspan in the document documentId, that requires rename in String or Comment
var stringAndCommentTextSpansInSingleSourceTree = renameLocations
.Where(l => l.DocumentId == documentId && l.IsRenameInStringOrComment)
.GroupBy(l => l.ContainingLocationForStringOrComment)
.ToImmutableDictionary(
g => g.Key,
g => GetSubSpansToRenameInStringAndCommentTextSpans(g.Key, g));
var conflictLocationSpans = _conflictLocations
.Where(t => t.DocumentId == documentId)
.Select(t => t.ComplexifiedSpan).ToSet();
// Annotate all nodes with a RenameLocation annotations to record old locations & old referenced symbols.
// Also annotate nodes that should get complexified (nodes for rename locations + conflict locations)
var parameters = new RenameRewriterParameters(
_renamedSymbolDeclarationAnnotation,
document,
semanticModel,
originalSyntaxRoot,
_replacementText,
_originalText,
_possibleNameConflicts,
allTextSpansInSingleSourceTree,
stringAndCommentTextSpansInSingleSourceTree,
conflictLocationSpans,
originalSolution,
_renameLocationSet.Symbol,
replacementTextValid,
renameSpansTracker,
_optionSet,
_renameAnnotations,
_cancellationToken);
var renameRewriterLanguageService = document.GetRequiredLanguageService<IRenameRewriterLanguageService>();
var newRoot = renameRewriterLanguageService.AnnotateAndRename(parameters);
if (newRoot == originalSyntaxRoot)
{
// Update the list for the current phase, some files with strings containing the original or replacement
// text may have been filtered out.
documentIdsToRename.Remove(documentId);
}
else
{
partiallyRenamedSolution = partiallyRenamedSolution.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity);
}
}
return partiallyRenamedSolution;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// We try to rewrite all locations that are invalid candidate locations. If there is only
/// one location it must be the correct one (the symbol is ambiguous to something else)
/// and we always try to rewrite it. If there are multiple locations, we only allow it
/// if the candidate reason allows for it).
private static bool ShouldIncludeLocation(ISet<RenameLocation> renameLocations, RenameLocation location)
{
if (location.IsRenameInStringOrComment)
{
return false;
}
if (renameLocations.Count == 1)
{
return true;
}
return RenameLocation.ShouldRename(location);
}
/// <summary>
/// We try to compute the sub-spans to rename within the given <paramref name="containingLocationForStringOrComment"/>.
/// If we are renaming within a string, the locations to rename are always within this containing string location
/// and we can identify these sub-spans.
/// However, if we are renaming within a comment, the rename locations can be anywhere in trivia,
/// so we return null and the rename rewriter will perform a complete regex match within comment trivia
/// and rename all matches instead of specific matches.
/// </summary>
private static ImmutableSortedSet<TextSpan>? GetSubSpansToRenameInStringAndCommentTextSpans(
TextSpan containingLocationForStringOrComment,
IEnumerable<RenameLocation> locationsToRename)
{
var builder = ImmutableSortedSet.CreateBuilder<TextSpan>();
foreach (var renameLocation in locationsToRename)
{
if (!containingLocationForStringOrComment.Contains(renameLocation.Location.SourceSpan))
{
// We found a location outside the 'containingLocationForStringOrComment',
// which is likely in trivia.
// Bail out from computing specific sub-spans and let the rename rewriter
// do a full regex match and replace.
return null;
}
// Compute the sub-span within 'containingLocationForStringOrComment' that needs to be renamed.
var offset = renameLocation.Location.SourceSpan.Start - containingLocationForStringOrComment.Start;
var length = renameLocation.Location.SourceSpan.Length;
var subSpan = new TextSpan(offset, length);
builder.Add(subSpan);
}
return builder.ToImmutable();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Rename.ConflictEngine
{
internal static partial class ConflictResolver
{
/// <summary>
/// Helper class to track the state necessary for finding/resolving conflicts in a
/// rename session.
/// </summary>
private class Session
{
// Set of All Locations that will be renamed (does not include non-reference locations that need to be checked for conflicts)
private readonly RenameLocations _renameLocationSet;
// Rename Symbol's Source Location
private readonly Location _renameSymbolDeclarationLocation;
private readonly DocumentId _documentIdOfRenameSymbolDeclaration;
private readonly string _originalText;
private readonly string _replacementText;
private readonly RenameOptionSet _optionSet;
private readonly ImmutableHashSet<ISymbol>? _nonConflictSymbols;
private readonly CancellationToken _cancellationToken;
private readonly RenameAnnotation _renamedSymbolDeclarationAnnotation;
// Contains Strings like Bar -> BarAttribute ; Property Bar -> Bar , get_Bar, set_Bar
private readonly List<string> _possibleNameConflicts;
private readonly HashSet<DocumentId> _documentsIdsToBeCheckedForConflict;
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
private ISet<ConflictLocationInfo> _conflictLocations;
private bool _replacementTextValid;
private List<ProjectId>? _topologicallySortedProjects;
private bool _documentOfRenameSymbolHasBeenRenamed;
public Session(
RenameLocations renameLocationSet,
Location renameSymbolDeclarationLocation,
string replacementText,
ImmutableHashSet<ISymbol>? nonConflictSymbols,
CancellationToken cancellationToken)
{
_renameLocationSet = renameLocationSet;
_renameSymbolDeclarationLocation = renameSymbolDeclarationLocation;
_originalText = renameLocationSet.Symbol.Name;
_replacementText = replacementText;
_optionSet = renameLocationSet.Options;
_nonConflictSymbols = nonConflictSymbols;
_cancellationToken = cancellationToken;
_renamedSymbolDeclarationAnnotation = new RenameAnnotation();
_conflictLocations = SpecializedCollections.EmptySet<ConflictLocationInfo>();
_replacementTextValid = true;
_possibleNameConflicts = new List<string>();
// only process documents which possibly contain the identifiers.
_documentsIdsToBeCheckedForConflict = new HashSet<DocumentId>();
_documentIdOfRenameSymbolDeclaration = renameLocationSet.Solution.GetRequiredDocument(renameSymbolDeclarationLocation.SourceTree!).Id;
_renameAnnotations = new AnnotationTable<RenameAnnotation>(RenameAnnotation.Kind);
}
private struct ConflictLocationInfo
{
// The span of the Node that needs to be complexified
public readonly TextSpan ComplexifiedSpan;
public readonly DocumentId DocumentId;
// The identifier span that needs to be checked for conflict
public readonly TextSpan OriginalIdentifierSpan;
public ConflictLocationInfo(RelatedLocation location)
{
Debug.Assert(location.ComplexifiedTargetSpan.Contains(location.ConflictCheckSpan) || location.Type == RelatedLocationType.UnresolvableConflict);
this.ComplexifiedSpan = location.ComplexifiedTargetSpan;
this.DocumentId = location.DocumentId;
this.OriginalIdentifierSpan = location.ConflictCheckSpan;
}
}
// The method which performs rename, resolves the conflict locations and returns the result of the rename operation
public async Task<MutableConflictResolution> ResolveConflictsAsync()
{
try
{
await FindDocumentsAndPossibleNameConflictsAsync().ConfigureAwait(false);
var baseSolution = _renameLocationSet.Solution;
// Process rename one project at a time to improve caching and reduce syntax tree serialization.
RoslynDebug.Assert(_topologicallySortedProjects != null);
var documentsGroupedByTopologicallySortedProjectId = _documentsIdsToBeCheckedForConflict
.GroupBy(d => d.ProjectId)
.OrderBy(g => _topologicallySortedProjects.IndexOf(g.Key));
_replacementTextValid = IsIdentifierValid_Worker(baseSolution, _replacementText, documentsGroupedByTopologicallySortedProjectId.Select(g => g.Key));
var renamedSpansTracker = new RenamedSpansTracker();
var conflictResolution = new MutableConflictResolution(baseSolution, renamedSpansTracker, _replacementText, _replacementTextValid);
var intermediateSolution = conflictResolution.OldSolution;
foreach (var documentsByProject in documentsGroupedByTopologicallySortedProjectId)
{
var documentIdsThatGetsAnnotatedAndRenamed = new HashSet<DocumentId>(documentsByProject);
using (baseSolution.Services.CacheService?.EnableCaching(documentsByProject.Key))
{
// Rename is going to be in 5 phases.
// 1st phase - Does a simple token replacement
// If the 1st phase results in conflict then we perform then:
// 2nd phase is to expand and simplify only the reference locations with conflicts
// 3rd phase is to expand and simplify all the conflict locations (both reference and non-reference)
// If there are unresolved Conflicts after the 3rd phase then in 4th phase,
// We complexify and resolve locations that were resolvable and for the other locations we perform the normal token replacement like the first the phase.
// If the OptionSet has RenameFile to true, we rename files with the type declaration
for (var phase = 0; phase < 4; phase++)
{
// Step 1:
// The rename process and annotation for the bookkeeping is performed in one-step
// The Process in short is,
// 1. If renaming a token which is no conflict then replace the token and make a map of the oldspan to the newspan
// 2. If we encounter a node that has to be expanded( because there was a conflict in previous phase), we expand it.
// If the node happens to contain a token that needs to be renamed then we annotate it and rename it after expansion else just expand and proceed
// 3. Through the whole process we maintain a map of the oldspan to newspan. In case of expansion & rename, we map the expanded node and the renamed token
conflictResolution.UpdateCurrentSolution(await AnnotateAndRename_WorkerAsync(
baseSolution,
conflictResolution.CurrentSolution,
documentIdsThatGetsAnnotatedAndRenamed,
_renameLocationSet.Locations,
renamedSpansTracker,
_replacementTextValid).ConfigureAwait(false));
// Step 2: Check for conflicts in the renamed solution
var foundResolvableConflicts = await IdentifyConflictsAsync(
documentIdsForConflictResolution: documentIdsThatGetsAnnotatedAndRenamed,
allDocumentIdsInProject: documentsByProject,
projectId: documentsByProject.Key,
conflictResolution: conflictResolution).ConfigureAwait(false);
if (!foundResolvableConflicts || phase == 3)
{
break;
}
if (phase == 0)
{
_conflictLocations = conflictResolution.RelatedLocations
.Where(loc => (documentIdsThatGetsAnnotatedAndRenamed.Contains(loc.DocumentId) && loc.Type == RelatedLocationType.PossiblyResolvableConflict && loc.IsReference))
.Select(loc => new ConflictLocationInfo(loc))
.ToSet();
// If there were no conflicting locations in references, then the first conflict phase has to be skipped.
if (_conflictLocations.Count == 0)
{
phase++;
}
}
if (phase == 1)
{
_conflictLocations = _conflictLocations.Concat(conflictResolution.RelatedLocations
.Where(loc => documentIdsThatGetsAnnotatedAndRenamed.Contains(loc.DocumentId) && loc.Type == RelatedLocationType.PossiblyResolvableConflict)
.Select(loc => new ConflictLocationInfo(loc)))
.ToSet();
}
// Set the documents with conflicts that need to be processed in the next phase.
// Note that we need to get the conflictLocations here since we're going to remove some locations below if phase == 2
documentIdsThatGetsAnnotatedAndRenamed = new HashSet<DocumentId>(_conflictLocations.Select(l => l.DocumentId));
if (phase == 2)
{
// After phase 2, if there are still conflicts then remove the conflict locations from being expanded
var unresolvedLocations = conflictResolution.RelatedLocations
.Where(l => (l.Type & RelatedLocationType.UnresolvedConflict) != 0)
.Select(l => Tuple.Create(l.ComplexifiedTargetSpan, l.DocumentId)).Distinct();
_conflictLocations = _conflictLocations.Where(l => !unresolvedLocations.Any(c => c.Item2 == l.DocumentId && c.Item1.Contains(l.OriginalIdentifierSpan))).ToSet();
}
// Clean up side effects from rename before entering the next phase
conflictResolution.ClearDocuments(documentIdsThatGetsAnnotatedAndRenamed);
}
// Step 3: Simplify the project
conflictResolution.UpdateCurrentSolution(await renamedSpansTracker.SimplifyAsync(conflictResolution.CurrentSolution, documentsByProject, _replacementTextValid, _renameAnnotations, _cancellationToken).ConfigureAwait(false));
intermediateSolution = await conflictResolution.RemoveAllRenameAnnotationsAsync(
intermediateSolution, documentsByProject, _renameAnnotations, _cancellationToken).ConfigureAwait(false);
conflictResolution.UpdateCurrentSolution(intermediateSolution);
}
}
// This rename could break implicit references of this symbol (e.g. rename MoveNext on a collection like type in a
// foreach/for each statement
var renamedSymbolInNewSolution = await GetRenamedSymbolInCurrentSolutionAsync(conflictResolution).ConfigureAwait(false);
if (IsRenameValid(conflictResolution, renamedSymbolInNewSolution))
{
await AddImplicitConflictsAsync(
renamedSymbolInNewSolution,
_renameLocationSet.Symbol,
_renameLocationSet.ImplicitLocations,
await conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration).GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false),
_renameSymbolDeclarationLocation,
renamedSpansTracker.GetAdjustedPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration),
conflictResolution,
_cancellationToken).ConfigureAwait(false);
}
for (var i = 0; i < conflictResolution.RelatedLocations.Count; i++)
{
var relatedLocation = conflictResolution.RelatedLocations[i];
if (relatedLocation.Type == RelatedLocationType.PossiblyResolvableConflict)
conflictResolution.RelatedLocations[i] = relatedLocation.WithType(RelatedLocationType.UnresolvedConflict);
}
#if DEBUG
await DebugVerifyNoErrorsAsync(conflictResolution, _documentsIdsToBeCheckedForConflict).ConfigureAwait(false);
#endif
// Step 5: Rename declaration files
if (_optionSet.RenameFile)
{
var definitionLocations = _renameLocationSet.Symbol.Locations;
var definitionDocuments = definitionLocations
.Select(l => conflictResolution.OldSolution.GetDocument(l.SourceTree))
.Distinct();
if (definitionDocuments.Count() == 1 && _replacementTextValid)
{
// At the moment, only single document renaming is allowed
conflictResolution.RenameDocumentToMatchNewSymbol(definitionDocuments.Single());
}
}
return conflictResolution;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
#if DEBUG
private async Task DebugVerifyNoErrorsAsync(MutableConflictResolution conflictResolution, IEnumerable<DocumentId> documents)
{
var documentIdErrorStateLookup = new Dictionary<DocumentId, bool>();
// we only check for the documentIds we add annotations to, which is a subset of the ones we're going
// to change the syntax in.
foreach (var documentId in documents)
{
// remember if there were issues in the document prior to renaming it.
var originalDoc = conflictResolution.OldSolution.GetRequiredDocument(documentId);
documentIdErrorStateLookup.Add(documentId, await originalDoc.HasAnyErrorsAsync(_cancellationToken).ConfigureAwait(false));
}
// We want to ignore few error message introduced by rename because the user is wantedly doing it.
var ignoreErrorCodes = new List<string>();
ignoreErrorCodes.Add("BC30420"); // BC30420 - Sub Main missing in VB Project
ignoreErrorCodes.Add("CS5001"); // CS5001 - Missing Main in C# Project
// only check if rename thinks it was successful
if (conflictResolution.ReplacementTextValid && conflictResolution.RelatedLocations.All(loc => (loc.Type & RelatedLocationType.UnresolvableConflict) == 0))
{
foreach (var documentId in documents)
{
// only check documents that had no errors before rename (we might have
// fixed them because of rename). Also, don't bother checking if a custom
// callback was provided. The caller might be ok with a rename that introduces
// errors.
if (!documentIdErrorStateLookup[documentId] && _nonConflictSymbols == null)
{
await conflictResolution.CurrentSolution.GetRequiredDocument(documentId).VerifyNoErrorsAsync("Rename introduced errors in error-free code", _cancellationToken, ignoreErrorCodes).ConfigureAwait(false);
}
}
}
}
#endif
/// <summary>
/// Find conflicts in the new solution
/// </summary>
private async Task<bool> IdentifyConflictsAsync(
HashSet<DocumentId> documentIdsForConflictResolution,
IEnumerable<DocumentId> allDocumentIdsInProject,
ProjectId projectId,
MutableConflictResolution conflictResolution)
{
try
{
_documentOfRenameSymbolHasBeenRenamed |= documentIdsForConflictResolution.Contains(_documentIdOfRenameSymbolDeclaration);
// Get the renamed symbol in complexified new solution
var renamedSymbolInNewSolution = await GetRenamedSymbolInCurrentSolutionAsync(conflictResolution).ConfigureAwait(false);
// if the text replacement is invalid, we just did a simple token replacement.
// Therefore we don't need more mapping information and can skip the rest of
// the loop body.
if (!IsRenameValid(conflictResolution, renamedSymbolInNewSolution))
{
foreach (var documentId in documentIdsForConflictResolution)
{
var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(documentId);
var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot);
foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations)
{
if (annotation.IsRenameLocation)
{
conflictResolution.AddRelatedLocation(new RelatedLocation(
annotation.OriginalSpan, documentId, RelatedLocationType.UnresolvedConflict));
}
}
}
return false;
}
var reverseMappedLocations = new Dictionary<Location, Location>();
// If we were giving any non-conflict-symbols then ensure that we know what those symbols are in
// the current project post after our edits so far.
var currentProject = conflictResolution.CurrentSolution.GetRequiredProject(projectId);
var nonConflictSymbols = await GetNonConflictSymbolsAsync(currentProject).ConfigureAwait(false);
foreach (var documentId in documentIdsForConflictResolution)
{
var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(documentId);
var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var baseDocument = conflictResolution.OldSolution.GetRequiredDocument(documentId);
var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);
var baseRoot = await baseDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
SemanticModel? newDocumentSemanticModel = null;
var syntaxFactsService = newDocument.Project.LanguageServices.GetRequiredService<ISyntaxFactsService>();
// Get all tokens that need conflict check
var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot);
var complexifiedLocationSpanForThisDocument =
_conflictLocations
.Where(t => t.DocumentId == documentId)
.Select(t => t.OriginalIdentifierSpan).ToSet();
foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations)
{
var tokenOrNode = syntax;
var conflictAnnotation = annotation;
reverseMappedLocations[tokenOrNode.GetLocation()!] = baseSyntaxTree.GetLocation(conflictAnnotation.OriginalSpan);
var originalLocation = conflictAnnotation.OriginalSpan;
ImmutableArray<ISymbol> newReferencedSymbols = default;
var hasConflict = _renameAnnotations.HasAnnotation(tokenOrNode, RenameInvalidIdentifierAnnotation.Instance);
if (!hasConflict)
{
newDocumentSemanticModel ??= await newDocument.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
newReferencedSymbols = GetSymbolsInNewSolution(newDocument, newDocumentSemanticModel, conflictAnnotation, tokenOrNode);
// The semantic correctness, after rename, for each token of interest in the
// rename context is performed by getting the symbol pointed by each token
// and obtain the Symbol's First Ordered Location's Span-Start and check to
// see if it is the same as before from the base solution. During rename,
// the spans would have been modified and so we need to adjust the old position
// to the new position for which we use the renameSpanTracker, which was tracking
// & mapping the old span -> new span during rename
hasConflict =
!IsConflictFreeChange(newReferencedSymbols, nonConflictSymbols) &&
await CheckForConflictAsync(conflictResolution, renamedSymbolInNewSolution, conflictAnnotation, newReferencedSymbols).ConfigureAwait(false);
if (!hasConflict && !conflictAnnotation.IsInvocationExpression)
hasConflict = LocalVariableConflictPerLanguage((SyntaxToken)tokenOrNode, newDocument, newReferencedSymbols);
}
if (!hasConflict)
{
if (conflictAnnotation.IsRenameLocation)
{
conflictResolution.AddRelatedLocation(
new RelatedLocation(originalLocation,
documentId,
complexifiedLocationSpanForThisDocument.Contains(originalLocation) ? RelatedLocationType.ResolvedReferenceConflict : RelatedLocationType.NoConflict,
isReference: true));
}
else
{
// if a complexified location was not a reference location, then it was a resolved conflict of a non reference location
if (!conflictAnnotation.IsOriginalTextLocation && complexifiedLocationSpanForThisDocument.Contains(originalLocation))
{
conflictResolution.AddRelatedLocation(
new RelatedLocation(originalLocation,
documentId,
RelatedLocationType.ResolvedNonReferenceConflict,
isReference: false));
}
}
}
else
{
var baseToken = baseRoot.FindToken(conflictAnnotation.OriginalSpan.Start, true);
var complexifiedTarget = GetExpansionTargetForLocationPerLanguage(baseToken, baseDocument);
conflictResolution.AddRelatedLocation(new RelatedLocation(
originalLocation,
documentId,
complexifiedTarget != null ? RelatedLocationType.PossiblyResolvableConflict : RelatedLocationType.UnresolvableConflict,
isReference: conflictAnnotation.IsRenameLocation,
complexifiedTargetSpan: complexifiedTarget != null ? complexifiedTarget.Span : default));
}
}
}
// there are more conflicts that cannot be identified by checking if the tokens still reference the same
// symbol. These conflicts are mostly language specific. A good example is a member with the same name
// as the parent (yes I know, this is a simplification).
if (_documentIdOfRenameSymbolDeclaration.ProjectId == projectId)
{
// Calculating declaration conflicts may require location mapping in documents
// that were not otherwise being processed in the current rename phase, so add
// the annotated spans in these documents to reverseMappedLocations.
foreach (var unprocessedDocumentIdWithPotentialDeclarationConflicts in allDocumentIdsInProject.Where(d => !documentIdsForConflictResolution.Contains(d)))
{
var newDocument = conflictResolution.CurrentSolution.GetRequiredDocument(unprocessedDocumentIdWithPotentialDeclarationConflicts);
var syntaxRoot = await newDocument.GetRequiredSyntaxRootAsync(_cancellationToken).ConfigureAwait(false);
var baseDocument = conflictResolution.OldSolution.GetRequiredDocument(unprocessedDocumentIdWithPotentialDeclarationConflicts);
var baseSyntaxTree = await baseDocument.GetRequiredSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);
var nodesOrTokensWithConflictCheckAnnotations = GetNodesOrTokensToCheckForConflicts(syntaxRoot);
foreach (var (syntax, annotation) in nodesOrTokensWithConflictCheckAnnotations)
{
var tokenOrNode = syntax;
var conflictAnnotation = annotation;
reverseMappedLocations[tokenOrNode.GetLocation()!] = baseSyntaxTree.GetLocation(conflictAnnotation.OriginalSpan);
}
}
var referencedSymbols = _renameLocationSet.ReferencedSymbols;
var renameSymbol = _renameLocationSet.Symbol;
await AddDeclarationConflictsAsync(
renamedSymbolInNewSolution, renameSymbol, referencedSymbols, conflictResolution, reverseMappedLocations, _cancellationToken).ConfigureAwait(false);
}
return conflictResolution.RelatedLocations.Any(r => r.Type == RelatedLocationType.PossiblyResolvableConflict);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<ImmutableHashSet<ISymbol>?> GetNonConflictSymbolsAsync(Project currentProject)
{
if (_nonConflictSymbols == null)
return null;
var compilation = await currentProject.GetRequiredCompilationAsync(_cancellationToken).ConfigureAwait(false);
return ImmutableHashSet.CreateRange(
_nonConflictSymbols.Select(s => s.GetSymbolKey().Resolve(compilation).GetAnySymbol()).WhereNotNull());
}
private bool IsConflictFreeChange(
ImmutableArray<ISymbol> symbols, ImmutableHashSet<ISymbol>? nonConflictSymbols)
{
if (_nonConflictSymbols != null)
{
RoslynDebug.Assert(nonConflictSymbols != null);
foreach (var symbol in symbols)
{
// Reference not points at a symbol in the conflict-free list. This is a conflict-free change.
if (nonConflictSymbols.Contains(symbol))
return true;
}
}
// Just do the default check.
return false;
}
/// <summary>
/// Gets the list of the nodes that were annotated for a conflict check
/// </summary>
private IEnumerable<(SyntaxNodeOrToken syntax, RenameActionAnnotation annotation)> GetNodesOrTokensToCheckForConflicts(
SyntaxNode syntaxRoot)
{
return syntaxRoot.DescendantNodesAndTokens(descendIntoTrivia: true)
.Where(s => _renameAnnotations.HasAnnotations<RenameActionAnnotation>(s))
.Select(s => (s, _renameAnnotations.GetAnnotations<RenameActionAnnotation>(s).Single()));
}
private async Task<bool> CheckForConflictAsync(
MutableConflictResolution conflictResolution,
ISymbol renamedSymbolInNewSolution,
RenameActionAnnotation conflictAnnotation,
ImmutableArray<ISymbol> newReferencedSymbols)
{
try
{
bool hasConflict;
var solution = conflictResolution.CurrentSolution;
if (conflictAnnotation.IsNamespaceDeclarationReference)
{
hasConflict = false;
}
else if (conflictAnnotation.IsMemberGroupReference)
{
if (!conflictAnnotation.RenameDeclarationLocationReferences.Any())
{
hasConflict = false;
}
else
{
// Ensure newReferencedSymbols contains at least one of the original referenced
// symbols, and allow any new symbols to be added to the set of references.
hasConflict = true;
var newLocationTasks = newReferencedSymbols.Select(async symbol => await GetSymbolLocationAsync(solution, symbol, _cancellationToken).ConfigureAwait(false));
var newLocations = (await Task.WhenAll(newLocationTasks).ConfigureAwait(false)).WhereNotNull().Where(loc => loc.IsInSource);
foreach (var originalReference in conflictAnnotation.RenameDeclarationLocationReferences.Where(loc => loc.IsSourceLocation))
{
var adjustedStartPosition = conflictResolution.GetAdjustedTokenStartingPosition(originalReference.TextSpan.Start, originalReference.DocumentId);
if (newLocations.Any(loc => loc.SourceSpan.Start == adjustedStartPosition))
{
hasConflict = false;
break;
}
}
}
}
else if (!conflictAnnotation.IsRenameLocation && conflictAnnotation.IsOriginalTextLocation && conflictAnnotation.RenameDeclarationLocationReferences.Length > 1 && newReferencedSymbols.Length == 1)
{
// an ambiguous situation was resolved through rename in non reference locations
hasConflict = false;
}
else if (newReferencedSymbols.Length != conflictAnnotation.RenameDeclarationLocationReferences.Length)
{
// Don't show conflicts for errors in the old solution that now bind in the new solution.
if (newReferencedSymbols.Length != 0 && conflictAnnotation.RenameDeclarationLocationReferences.Length == 0)
{
hasConflict = false;
}
else
{
hasConflict = true;
}
}
else
{
hasConflict = false;
var symbolIndex = 0;
foreach (var symbol in newReferencedSymbols)
{
if (conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].SymbolLocationsCount != symbol.Locations.Length)
{
hasConflict = true;
break;
}
var newLocation = await GetSymbolLocationAsync(solution, symbol, _cancellationToken).ConfigureAwait(false);
if (newLocation != null && conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].IsSourceLocation)
{
// location was in source before, but not after rename
if (!newLocation.IsInSource)
{
hasConflict = true;
break;
}
var renameDeclarationLocationReference = conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex];
var newAdjustedStartPosition = conflictResolution.GetAdjustedTokenStartingPosition(renameDeclarationLocationReference.TextSpan.Start, renameDeclarationLocationReference.DocumentId);
if (newAdjustedStartPosition != newLocation.SourceSpan.Start)
{
hasConflict = true;
break;
}
if (conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].IsOverriddenFromMetadata)
{
var overridingSymbol = await SymbolFinder.FindSymbolAtPositionAsync(solution.GetRequiredDocument(newLocation.SourceTree), newLocation.SourceSpan.Start, cancellationToken: _cancellationToken).ConfigureAwait(false);
if (overridingSymbol != null && !Equals(renamedSymbolInNewSolution, overridingSymbol))
{
if (!overridingSymbol.IsOverride)
{
hasConflict = true;
break;
}
else
{
var overriddenSymbol = overridingSymbol.GetOverriddenMember();
if (overriddenSymbol == null || !overriddenSymbol.Locations.All(loc => loc.IsInMetadata))
{
hasConflict = true;
break;
}
}
}
}
}
else
{
var newMetadataName = symbol.ToDisplayString(s_metadataSymbolDisplayFormat);
var oldMetadataName = conflictAnnotation.RenameDeclarationLocationReferences[symbolIndex].Name;
if (newLocation == null ||
newLocation.IsInSource ||
!HeuristicMetadataNameEquivalenceCheck(
oldMetadataName,
newMetadataName,
_originalText,
_replacementText))
{
hasConflict = true;
break;
}
}
symbolIndex++;
}
}
return hasConflict;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private ImmutableArray<ISymbol> GetSymbolsInNewSolution(Document newDocument, SemanticModel newDocumentSemanticModel, RenameActionAnnotation conflictAnnotation, SyntaxNodeOrToken tokenOrNode)
{
var newReferencedSymbols = RenameUtilities.GetSymbolsTouchingPosition(tokenOrNode.Span.Start, newDocumentSemanticModel, newDocument.Project.Solution.Workspace, _cancellationToken);
if (conflictAnnotation.IsInvocationExpression)
{
if (tokenOrNode.IsNode)
{
var invocationReferencedSymbols = SymbolsForEnclosingInvocationExpressionWorker((SyntaxNode)tokenOrNode!, newDocumentSemanticModel, _cancellationToken);
if (!invocationReferencedSymbols.IsDefault)
newReferencedSymbols = invocationReferencedSymbols;
}
}
// if there are more than one symbol, then remove the alias symbols.
// When using (not declaring) an alias, the alias symbol and the target symbol are returned
// by GetSymbolsTouchingPosition
if (newReferencedSymbols.Length >= 2)
newReferencedSymbols = newReferencedSymbols.WhereAsArray(a => a.Kind != SymbolKind.Alias);
return newReferencedSymbols;
}
private async Task<ISymbol> GetRenamedSymbolInCurrentSolutionAsync(MutableConflictResolution conflictResolution)
{
try
{
// get the renamed symbol in complexified new solution
var start = _documentOfRenameSymbolHasBeenRenamed
? conflictResolution.GetAdjustedTokenStartingPosition(_renameSymbolDeclarationLocation.SourceSpan.Start, _documentIdOfRenameSymbolDeclaration)
: _renameSymbolDeclarationLocation.SourceSpan.Start;
var document = conflictResolution.CurrentSolution.GetRequiredDocument(_documentIdOfRenameSymbolDeclaration);
var newSymbol = await SymbolFinder.FindSymbolAtPositionAsync(document, start, cancellationToken: _cancellationToken).ConfigureAwait(false);
return newSymbol;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// The method determines the set of documents that need to be processed for Rename and also determines
/// the possible set of names that need to be checked for conflicts.
/// </summary>
private async Task FindDocumentsAndPossibleNameConflictsAsync()
{
try
{
var symbol = _renameLocationSet.Symbol;
var solution = _renameLocationSet.Solution;
var dependencyGraph = solution.GetProjectDependencyGraph();
_topologicallySortedProjects = dependencyGraph.GetTopologicallySortedProjects(_cancellationToken).ToList();
var allRenamedDocuments = _renameLocationSet.Locations.Select(loc => loc.Location.SourceTree!).Distinct().Select(solution.GetRequiredDocument);
_documentsIdsToBeCheckedForConflict.AddRange(allRenamedDocuments.Select(d => d.Id));
var documentsFromAffectedProjects = RenameUtilities.GetDocumentsAffectedByRename(symbol, solution, _renameLocationSet.Locations);
foreach (var language in documentsFromAffectedProjects.Select(d => d.Project.Language).Distinct())
{
solution.Workspace.Services.GetLanguageServices(language).GetService<IRenameRewriterLanguageService>()
?.TryAddPossibleNameConflicts(symbol, _replacementText, _possibleNameConflicts);
}
await AddDocumentsWithPotentialConflictsAsync(documentsFromAffectedProjects).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AddDocumentsWithPotentialConflictsAsync(IEnumerable<Document> documents)
{
try
{
foreach (var document in documents)
{
if (_documentsIdsToBeCheckedForConflict.Contains(document.Id))
continue;
if (!document.SupportsSyntaxTree)
continue;
var info = await SyntaxTreeIndex.GetRequiredIndexAsync(document, _cancellationToken).ConfigureAwait(false);
if (info.ProbablyContainsEscapedIdentifier(_originalText))
{
_documentsIdsToBeCheckedForConflict.Add(document.Id);
continue;
}
if (info.ProbablyContainsIdentifier(_replacementText))
{
_documentsIdsToBeCheckedForConflict.Add(document.Id);
continue;
}
foreach (var replacementName in _possibleNameConflicts)
{
if (info.ProbablyContainsIdentifier(replacementName))
{
_documentsIdsToBeCheckedForConflict.Add(document.Id);
break;
}
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
// The rename process and annotation for the bookkeeping is performed in one-step
private async Task<Solution> AnnotateAndRename_WorkerAsync(
Solution originalSolution,
Solution partiallyRenamedSolution,
HashSet<DocumentId> documentIdsToRename,
ISet<RenameLocation> renameLocations,
RenamedSpansTracker renameSpansTracker,
bool replacementTextValid)
{
try
{
foreach (var documentId in documentIdsToRename.ToList())
{
_cancellationToken.ThrowIfCancellationRequested();
var document = originalSolution.GetRequiredDocument(documentId);
var semanticModel = await document.GetRequiredSemanticModelAsync(_cancellationToken).ConfigureAwait(false);
var originalSyntaxRoot = await semanticModel.SyntaxTree.GetRootAsync(_cancellationToken).ConfigureAwait(false);
// Get all rename locations for the current document.
var allTextSpansInSingleSourceTree = renameLocations
.Where(l => l.DocumentId == documentId && ShouldIncludeLocation(renameLocations, l))
.ToDictionary(l => l.Location.SourceSpan);
// All textspan in the document documentId, that requires rename in String or Comment
var stringAndCommentTextSpansInSingleSourceTree = renameLocations
.Where(l => l.DocumentId == documentId && l.IsRenameInStringOrComment)
.GroupBy(l => l.ContainingLocationForStringOrComment)
.ToImmutableDictionary(
g => g.Key,
g => GetSubSpansToRenameInStringAndCommentTextSpans(g.Key, g));
var conflictLocationSpans = _conflictLocations
.Where(t => t.DocumentId == documentId)
.Select(t => t.ComplexifiedSpan).ToSet();
// Annotate all nodes with a RenameLocation annotations to record old locations & old referenced symbols.
// Also annotate nodes that should get complexified (nodes for rename locations + conflict locations)
var parameters = new RenameRewriterParameters(
_renamedSymbolDeclarationAnnotation,
document,
semanticModel,
originalSyntaxRoot,
_replacementText,
_originalText,
_possibleNameConflicts,
allTextSpansInSingleSourceTree,
stringAndCommentTextSpansInSingleSourceTree,
conflictLocationSpans,
originalSolution,
_renameLocationSet.Symbol,
replacementTextValid,
renameSpansTracker,
_optionSet,
_renameAnnotations,
_cancellationToken);
var renameRewriterLanguageService = document.GetRequiredLanguageService<IRenameRewriterLanguageService>();
var newRoot = renameRewriterLanguageService.AnnotateAndRename(parameters);
if (newRoot == originalSyntaxRoot)
{
// Update the list for the current phase, some files with strings containing the original or replacement
// text may have been filtered out.
documentIdsToRename.Remove(documentId);
}
else
{
partiallyRenamedSolution = partiallyRenamedSolution.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity);
}
}
return partiallyRenamedSolution;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// We try to rewrite all locations that are invalid candidate locations. If there is only
/// one location it must be the correct one (the symbol is ambiguous to something else)
/// and we always try to rewrite it. If there are multiple locations, we only allow it
/// if the candidate reason allows for it).
private static bool ShouldIncludeLocation(ISet<RenameLocation> renameLocations, RenameLocation location)
{
if (location.IsRenameInStringOrComment)
{
return false;
}
if (renameLocations.Count == 1)
{
return true;
}
return RenameLocation.ShouldRename(location);
}
/// <summary>
/// We try to compute the sub-spans to rename within the given <paramref name="containingLocationForStringOrComment"/>.
/// If we are renaming within a string, the locations to rename are always within this containing string location
/// and we can identify these sub-spans.
/// However, if we are renaming within a comment, the rename locations can be anywhere in trivia,
/// so we return null and the rename rewriter will perform a complete regex match within comment trivia
/// and rename all matches instead of specific matches.
/// </summary>
private static ImmutableSortedSet<TextSpan>? GetSubSpansToRenameInStringAndCommentTextSpans(
TextSpan containingLocationForStringOrComment,
IEnumerable<RenameLocation> locationsToRename)
{
var builder = ImmutableSortedSet.CreateBuilder<TextSpan>();
foreach (var renameLocation in locationsToRename)
{
if (!containingLocationForStringOrComment.Contains(renameLocation.Location.SourceSpan))
{
// We found a location outside the 'containingLocationForStringOrComment',
// which is likely in trivia.
// Bail out from computing specific sub-spans and let the rename rewriter
// do a full regex match and replace.
return null;
}
// Compute the sub-span within 'containingLocationForStringOrComment' that needs to be renamed.
var offset = renameLocation.Location.SourceSpan.Start - containingLocationForStringOrComment.Start;
var length = renameLocation.Location.SourceSpan.Length;
var subSpan = new TextSpan(offset, length);
builder.Add(subSpan);
}
return builder.ToImmutable();
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/IHierarchyItemToProjectIdMap.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
/// <summary>
/// Maps from hierarchy items to project IDs.
/// </summary>
internal interface IHierarchyItemToProjectIdMap : IWorkspaceService
{
/// <summary>
/// Given an <see cref="IVsHierarchyItem"/> representing a project and an optional target framework moniker,
/// returns the <see cref="ProjectId"/> of the equivalent Roslyn <see cref="Project"/>.
/// </summary>
/// <param name="hierarchyItem">An <see cref="IVsHierarchyItem"/> for the project root.</param>
/// <param name="targetFrameworkMoniker">An optional string representing a TargetFrameworkMoniker.
/// This is only useful in multi-targeting scenarios where there may be multiple Roslyn projects
/// (one per target framework) for a single project on disk.</param>
/// <param name="projectId">The <see cref="ProjectId"/> of the found project, if any.</param>
/// <returns>True if the desired project was found; false otherwise.</returns>
bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
/// <summary>
/// Maps from hierarchy items to project IDs.
/// </summary>
internal interface IHierarchyItemToProjectIdMap : IWorkspaceService
{
/// <summary>
/// Given an <see cref="IVsHierarchyItem"/> representing a project and an optional target framework moniker,
/// returns the <see cref="ProjectId"/> of the equivalent Roslyn <see cref="Project"/>.
/// </summary>
/// <param name="hierarchyItem">An <see cref="IVsHierarchyItem"/> for the project root.</param>
/// <param name="targetFrameworkMoniker">An optional string representing a TargetFrameworkMoniker.
/// This is only useful in multi-targeting scenarios where there may be multiple Roslyn projects
/// (one per target framework) for a single project on disk.</param>
/// <param name="projectId">The <see cref="ProjectId"/> of the found project, if any.</param>
/// <returns>True if the desired project was found; false otherwise.</returns>
bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Completion/ExportCompletionProviderAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// Use this attribute to export a <see cref="CompletionProvider"/> so that it will
/// be found and used by the per language associated <see cref="CompletionService"/>.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExportCompletionProviderAttribute : ExportAttribute
{
public string Name { get; }
public string Language { get; }
public string[] Roles { get; set; }
public ExportCompletionProviderAttribute(string name, string language)
: base(typeof(CompletionProvider))
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Completion
{
/// <summary>
/// Use this attribute to export a <see cref="CompletionProvider"/> so that it will
/// be found and used by the per language associated <see cref="CompletionService"/>.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public sealed class ExportCompletionProviderAttribute : ExportAttribute
{
public string Name { get; }
public string Language { get; }
public string[] Roles { get; set; }
public ExportCompletionProviderAttribute(string name, string language)
: base(typeof(CompletionProvider))
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/IGenerateConversionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
{
internal interface IGenerateConversionService : ILanguageService
{
Task<ImmutableArray<CodeAction>> GenerateConversionAsync(Document document, SyntaxNode node, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember
{
internal interface IGenerateConversionService : ILanguageService
{
Task<ImmutableArray<CodeAction>> GenerateConversionAsync(Document document, SyntaxNode node, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/Library/AbstractLibraryManager_IVsSimpleLibrary2.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library
{
internal partial class AbstractLibraryManager : IVsSimpleLibrary2
{
public abstract uint GetLibraryFlags();
protected abstract uint GetSupportedCategoryFields(uint category);
protected abstract IVsSimpleObjectList2 GetList(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch);
protected abstract uint GetUpdateCounter();
protected virtual int CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo)
{
ppNavInfo = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleLibrary2.AddBrowseContainer(VSCOMPONENTSELECTORDATA[] pcdComponent, ref uint pgrfOptions, out string pbstrComponentAdded)
{
pbstrComponentAdded = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleLibrary2.CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo)
=> CreateNavInfo(rgSymbolNodes, ulcNodes, out ppNavInfo);
int IVsSimpleLibrary2.GetBrowseContainersForHierarchy(IVsHierarchy pHierarchy, uint celt, VSBROWSECONTAINER[] rgBrowseContainers, uint[] pcActual)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.GetGuid(out Guid pguidLib)
{
pguidLib = this.LibraryGuid;
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.GetLibFlags2(out uint pgrfFlags)
{
pgrfFlags = GetLibraryFlags();
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.GetList2(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsSimpleObjectList2 ppIVsSimpleObjectList2)
{
ppIVsSimpleObjectList2 = GetList(listType, flags, pobSrch);
return ppIVsSimpleObjectList2 != null
? VSConstants.S_OK
: VSConstants.E_FAIL;
}
int IVsSimpleLibrary2.GetSeparatorStringWithOwnership(out string pbstrSeparator)
{
pbstrSeparator = ".";
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.GetSupportedCategoryFields2(int category, out uint pgrfCatField)
{
pgrfCatField = GetSupportedCategoryFields((uint)category);
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.LoadState(IStream pIStream, LIB_PERSISTTYPE lptType)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.RemoveBrowseContainer(uint dwReserved, string pszLibName)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.SaveState(IStream pIStream, LIB_PERSISTTYPE lptType)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.UpdateCounter(out uint pCurUpdate)
{
pCurUpdate = GetUpdateCounter();
return VSConstants.E_NOTIMPL;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library
{
internal partial class AbstractLibraryManager : IVsSimpleLibrary2
{
public abstract uint GetLibraryFlags();
protected abstract uint GetSupportedCategoryFields(uint category);
protected abstract IVsSimpleObjectList2 GetList(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch);
protected abstract uint GetUpdateCounter();
protected virtual int CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo)
{
ppNavInfo = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleLibrary2.AddBrowseContainer(VSCOMPONENTSELECTORDATA[] pcdComponent, ref uint pgrfOptions, out string pbstrComponentAdded)
{
pbstrComponentAdded = null;
return VSConstants.E_NOTIMPL;
}
int IVsSimpleLibrary2.CreateNavInfo(SYMBOL_DESCRIPTION_NODE[] rgSymbolNodes, uint ulcNodes, out IVsNavInfo ppNavInfo)
=> CreateNavInfo(rgSymbolNodes, ulcNodes, out ppNavInfo);
int IVsSimpleLibrary2.GetBrowseContainersForHierarchy(IVsHierarchy pHierarchy, uint celt, VSBROWSECONTAINER[] rgBrowseContainers, uint[] pcActual)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.GetGuid(out Guid pguidLib)
{
pguidLib = this.LibraryGuid;
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.GetLibFlags2(out uint pgrfFlags)
{
pgrfFlags = GetLibraryFlags();
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.GetList2(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsSimpleObjectList2 ppIVsSimpleObjectList2)
{
ppIVsSimpleObjectList2 = GetList(listType, flags, pobSrch);
return ppIVsSimpleObjectList2 != null
? VSConstants.S_OK
: VSConstants.E_FAIL;
}
int IVsSimpleLibrary2.GetSeparatorStringWithOwnership(out string pbstrSeparator)
{
pbstrSeparator = ".";
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.GetSupportedCategoryFields2(int category, out uint pgrfCatField)
{
pgrfCatField = GetSupportedCategoryFields((uint)category);
return VSConstants.S_OK;
}
int IVsSimpleLibrary2.LoadState(IStream pIStream, LIB_PERSISTTYPE lptType)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.RemoveBrowseContainer(uint dwReserved, string pszLibName)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.SaveState(IStream pIStream, LIB_PERSISTTYPE lptType)
=> VSConstants.E_NOTIMPL;
int IVsSimpleLibrary2.UpdateCounter(out uint pCurUpdate)
{
pCurUpdate = GetUpdateCounter();
return VSConstants.E_NOTIMPL;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Core/MarkedSource/SourceWithMarkedNodes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Roslyn.Test.Utilities
{
internal sealed partial class SourceWithMarkedNodes
{
/// <summary>
/// The source with markers stripped out, that was used to produce the tree
/// </summary>
public readonly string Source;
/// <summary>
/// The original input source, with markers in tact
/// </summary>
public readonly string Input;
public readonly SyntaxTree Tree;
public readonly ImmutableArray<MarkedSpan> MarkedSpans;
public readonly ImmutableArray<ValueTuple<TextSpan, int, int>> SpansAndKindsAndIds;
/// <summary>
/// Parses source code with markers for further processing
/// </summary>
/// <param name="markedSource">The marked source</param>
/// <param name="parser">Delegate to turn source code into a syntax tree</param>
/// <param name="getSyntaxKind">Delegate to turn a marker into a syntax kind</param>
/// <param name="removeTags">Whether to remove tags from the source, as distinct from replacing them with whitespace. Note that if this
/// value is true then any marked node other than the first, will have an incorrect offset.</param>
public SourceWithMarkedNodes(string markedSource, Func<string, SyntaxTree> parser, Func<string, int> getSyntaxKind, bool removeTags = false)
{
Source = removeTags ? RemoveTags(markedSource) : ClearTags(markedSource);
Input = markedSource;
Tree = parser(Source);
MarkedSpans = ImmutableArray.CreateRange(GetSpansRecursive(markedSource, 0, getSyntaxKind));
SpansAndKindsAndIds = ImmutableArray.CreateRange(MarkedSpans.Select(s => (s.MarkedSyntax, s.SyntaxKind, s.Id)));
}
private static IEnumerable<MarkedSpan> GetSpansRecursive(string markedSource, int offset, Func<string, int> getSyntaxKind)
{
foreach (var match in s_markerPattern.Matches(markedSource).ToEnumerable())
{
var tagName = match.Groups["TagName"];
var markedSyntax = match.Groups["MarkedSyntax"];
var syntaxKindOpt = match.Groups["SyntaxKind"].Value;
var idOpt = match.Groups["Id"].Value;
var id = string.IsNullOrEmpty(idOpt) ? 0 : int.Parse(idOpt);
var parentIdOpt = match.Groups["ParentId"].Value;
var parentId = string.IsNullOrEmpty(parentIdOpt) ? 0 : int.Parse(parentIdOpt);
var parsedKind = string.IsNullOrEmpty(syntaxKindOpt) ? 0 : getSyntaxKind(syntaxKindOpt);
int absoluteOffset = offset + markedSyntax.Index;
yield return new MarkedSpan(new TextSpan(absoluteOffset, markedSyntax.Length), new TextSpan(match.Index, match.Length), tagName.Value, parsedKind, id, parentId);
foreach (var nestedSpan in GetSpansRecursive(markedSyntax.Value, absoluteOffset, getSyntaxKind))
{
yield return nestedSpan;
}
}
}
internal static string RemoveTags(string source)
{
return s_tags.Replace(source, "");
}
internal static string ClearTags(string source)
{
return s_tags.Replace(source, m => new string(' ', m.Length));
}
private static readonly Regex s_tags = new Regex(
@"[<][/]?[NMCL][:]?[:\.A-Za-z0-9]*[>]",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
private static readonly Regex s_markerPattern = new Regex(
@"[<] # Open tag
(?<TagName>[NMCL]) # The actual tag name can be any of these letters
( # Start a group so that everything after the tag can be optional
[:] # A colon
(?<Id>[0-9]+) # The first number after the colon is the Id
([.](?<ParentId>[0-9]+))? # Digits after a decimal point are the parent Id
([:](?<SyntaxKind>[A-Za-z]+))? # A second colon separates the syntax kind
)? # Close the group for the things after the tag name
[>] # Close tag
( # Start a group so that the closing tag is optional
(?<MarkedSyntax>.*) # This matches the source within the tags
[<][/][NMCL][:]?(\k<Id>)* [>] # The closing tag with its optional Id
)? # End of the group for the closing tag",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
public ImmutableDictionary<SyntaxNode, int> MapSyntaxNodesToMarks()
{
var root = Tree.GetRoot();
var builder = ImmutableDictionary.CreateBuilder<SyntaxNode, int>();
for (int i = 0; i < SpansAndKindsAndIds.Length; i++)
{
var node = GetNode(root, SpansAndKindsAndIds[i]);
builder.Add(node, SpansAndKindsAndIds[i].Item3);
}
return builder.ToImmutableDictionary();
}
private SyntaxNode GetNode(SyntaxNode root, ValueTuple<TextSpan, int, int> spanAndKindAndId)
{
var node = root.FindNode(spanAndKindAndId.Item1, getInnermostNodeForTie: true);
if (spanAndKindAndId.Item2 == 0)
{
return node;
}
var nodeOfKind = node.FirstAncestorOrSelf<SyntaxNode>(n => n.RawKind == spanAndKindAndId.Item2);
Assert.NotNull(nodeOfKind);
return nodeOfKind;
}
public ImmutableDictionary<int, SyntaxNode> MapMarksToSyntaxNodes()
{
var root = Tree.GetRoot();
var builder = ImmutableDictionary.CreateBuilder<int, SyntaxNode>();
for (int i = 0; i < SpansAndKindsAndIds.Length; i++)
{
builder.Add(SpansAndKindsAndIds[i].Item3, GetNode(root, SpansAndKindsAndIds[i]));
}
return builder.ToImmutableDictionary();
}
public static Func<SyntaxNode, SyntaxNode> GetSyntaxMap(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1)
{
var map0 = source0.MapMarksToSyntaxNodes();
var map1 = source1.MapSyntaxNodesToMarks();
#if DUMP
Console.WriteLine("========");
#endif
return new Func<SyntaxNode, SyntaxNode>(node1 =>
{
if (map1.TryGetValue(node1, out var mark) && map0.TryGetValue(mark, out var result))
{
return result;
}
#if DUMP
Console.WriteLine($"? {node1.RawKind} [[{node1}]]");
#endif
return null;
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Roslyn.Test.Utilities
{
internal sealed partial class SourceWithMarkedNodes
{
/// <summary>
/// The source with markers stripped out, that was used to produce the tree
/// </summary>
public readonly string Source;
/// <summary>
/// The original input source, with markers in tact
/// </summary>
public readonly string Input;
public readonly SyntaxTree Tree;
public readonly ImmutableArray<MarkedSpan> MarkedSpans;
public readonly ImmutableArray<ValueTuple<TextSpan, int, int>> SpansAndKindsAndIds;
/// <summary>
/// Parses source code with markers for further processing
/// </summary>
/// <param name="markedSource">The marked source</param>
/// <param name="parser">Delegate to turn source code into a syntax tree</param>
/// <param name="getSyntaxKind">Delegate to turn a marker into a syntax kind</param>
/// <param name="removeTags">Whether to remove tags from the source, as distinct from replacing them with whitespace. Note that if this
/// value is true then any marked node other than the first, will have an incorrect offset.</param>
public SourceWithMarkedNodes(string markedSource, Func<string, SyntaxTree> parser, Func<string, int> getSyntaxKind, bool removeTags = false)
{
Source = removeTags ? RemoveTags(markedSource) : ClearTags(markedSource);
Input = markedSource;
Tree = parser(Source);
MarkedSpans = ImmutableArray.CreateRange(GetSpansRecursive(markedSource, 0, getSyntaxKind));
SpansAndKindsAndIds = ImmutableArray.CreateRange(MarkedSpans.Select(s => (s.MarkedSyntax, s.SyntaxKind, s.Id)));
}
private static IEnumerable<MarkedSpan> GetSpansRecursive(string markedSource, int offset, Func<string, int> getSyntaxKind)
{
foreach (var match in s_markerPattern.Matches(markedSource).ToEnumerable())
{
var tagName = match.Groups["TagName"];
var markedSyntax = match.Groups["MarkedSyntax"];
var syntaxKindOpt = match.Groups["SyntaxKind"].Value;
var idOpt = match.Groups["Id"].Value;
var id = string.IsNullOrEmpty(idOpt) ? 0 : int.Parse(idOpt);
var parentIdOpt = match.Groups["ParentId"].Value;
var parentId = string.IsNullOrEmpty(parentIdOpt) ? 0 : int.Parse(parentIdOpt);
var parsedKind = string.IsNullOrEmpty(syntaxKindOpt) ? 0 : getSyntaxKind(syntaxKindOpt);
int absoluteOffset = offset + markedSyntax.Index;
yield return new MarkedSpan(new TextSpan(absoluteOffset, markedSyntax.Length), new TextSpan(match.Index, match.Length), tagName.Value, parsedKind, id, parentId);
foreach (var nestedSpan in GetSpansRecursive(markedSyntax.Value, absoluteOffset, getSyntaxKind))
{
yield return nestedSpan;
}
}
}
internal static string RemoveTags(string source)
{
return s_tags.Replace(source, "");
}
internal static string ClearTags(string source)
{
return s_tags.Replace(source, m => new string(' ', m.Length));
}
private static readonly Regex s_tags = new Regex(
@"[<][/]?[NMCL][:]?[:\.A-Za-z0-9]*[>]",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
private static readonly Regex s_markerPattern = new Regex(
@"[<] # Open tag
(?<TagName>[NMCL]) # The actual tag name can be any of these letters
( # Start a group so that everything after the tag can be optional
[:] # A colon
(?<Id>[0-9]+) # The first number after the colon is the Id
([.](?<ParentId>[0-9]+))? # Digits after a decimal point are the parent Id
([:](?<SyntaxKind>[A-Za-z]+))? # A second colon separates the syntax kind
)? # Close the group for the things after the tag name
[>] # Close tag
( # Start a group so that the closing tag is optional
(?<MarkedSyntax>.*) # This matches the source within the tags
[<][/][NMCL][:]?(\k<Id>)* [>] # The closing tag with its optional Id
)? # End of the group for the closing tag",
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
public ImmutableDictionary<SyntaxNode, int> MapSyntaxNodesToMarks()
{
var root = Tree.GetRoot();
var builder = ImmutableDictionary.CreateBuilder<SyntaxNode, int>();
for (int i = 0; i < SpansAndKindsAndIds.Length; i++)
{
var node = GetNode(root, SpansAndKindsAndIds[i]);
builder.Add(node, SpansAndKindsAndIds[i].Item3);
}
return builder.ToImmutableDictionary();
}
private SyntaxNode GetNode(SyntaxNode root, ValueTuple<TextSpan, int, int> spanAndKindAndId)
{
var node = root.FindNode(spanAndKindAndId.Item1, getInnermostNodeForTie: true);
if (spanAndKindAndId.Item2 == 0)
{
return node;
}
var nodeOfKind = node.FirstAncestorOrSelf<SyntaxNode>(n => n.RawKind == spanAndKindAndId.Item2);
Assert.NotNull(nodeOfKind);
return nodeOfKind;
}
public ImmutableDictionary<int, SyntaxNode> MapMarksToSyntaxNodes()
{
var root = Tree.GetRoot();
var builder = ImmutableDictionary.CreateBuilder<int, SyntaxNode>();
for (int i = 0; i < SpansAndKindsAndIds.Length; i++)
{
builder.Add(SpansAndKindsAndIds[i].Item3, GetNode(root, SpansAndKindsAndIds[i]));
}
return builder.ToImmutableDictionary();
}
public static Func<SyntaxNode, SyntaxNode> GetSyntaxMap(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1)
{
var map0 = source0.MapMarksToSyntaxNodes();
var map1 = source1.MapSyntaxNodesToMarks();
#if DUMP
Console.WriteLine("========");
#endif
return new Func<SyntaxNode, SyntaxNode>(node1 =>
{
if (map1.TryGetValue(node1, out var mark) && map0.TryGetValue(mark, out var result))
{
return result;
}
#if DUMP
Console.WriteLine($"? {node1.RawKind} [[{node1}]]");
#endif
return null;
});
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayMiscellaneousOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies miscellaneous options about the format of symbol descriptions.
/// </summary>
[Flags]
public enum SymbolDisplayMiscellaneousOptions
{
/// <summary>
/// Specifies that no miscellaneous options should be applied.
/// </summary>
None = 0,
/// <summary>
/// Uses keywords for predefined types.
/// For example, "int" instead of "System.Int32" in C#
/// or "Integer" instead of "System.Integer" in Visual Basic.
/// </summary>
UseSpecialTypes = 1 << 0,
/// <summary>
/// Escapes identifiers that are also keywords.
/// For example, "@true" instead of "true" in C# or
/// "[True]" instead of "True" in Visual Basic.
/// </summary>
EscapeKeywordIdentifiers = 1 << 1,
/// <summary>
/// Displays asterisks between commas in multi-dimensional arrays.
/// For example, "int[][*,*]" instead of "int[][,]" in C# or
/// "Integer()(*,*)" instead of "Integer()(*,*) in Visual Basic.
/// </summary>
UseAsterisksInMultiDimensionalArrays = 1 << 2,
/// <summary>
/// Displays "?" for erroneous types that lack names (perhaps due to faulty metadata).
/// </summary>
UseErrorTypeSymbolName = 1 << 3,
/// <summary>
/// Displays attributes names without the "Attribute" suffix, if possible.
/// </summary>
/// <remarks>
/// Has no effect outside <see cref="ISymbol.ToMinimalDisplayString"/> and only applies
/// if the context location is one where an attribute ca be referenced without the suffix.
/// </remarks>
RemoveAttributeSuffix = 1 << 4,
/// <summary>
/// Displays <see cref="Nullable{T}"/> as a normal generic type, rather than with
/// the special question mark syntax.
/// </summary>
ExpandNullable = 1 << 5,
/// <summary>
/// Append '?' to nullable reference types.
/// </summary>
IncludeNullableReferenceTypeModifier = 1 << 6,
/// <summary>
/// Allow the use of <c>default</c> instead of <c>default(T)</c> where applicable.
/// </summary>
AllowDefaultLiteral = 1 << 7,
/// <summary>
/// Append '!' to non-nullable reference types.
/// </summary>
IncludeNotNullableReferenceTypeModifier = 1 << 8,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies miscellaneous options about the format of symbol descriptions.
/// </summary>
[Flags]
public enum SymbolDisplayMiscellaneousOptions
{
/// <summary>
/// Specifies that no miscellaneous options should be applied.
/// </summary>
None = 0,
/// <summary>
/// Uses keywords for predefined types.
/// For example, "int" instead of "System.Int32" in C#
/// or "Integer" instead of "System.Integer" in Visual Basic.
/// </summary>
UseSpecialTypes = 1 << 0,
/// <summary>
/// Escapes identifiers that are also keywords.
/// For example, "@true" instead of "true" in C# or
/// "[True]" instead of "True" in Visual Basic.
/// </summary>
EscapeKeywordIdentifiers = 1 << 1,
/// <summary>
/// Displays asterisks between commas in multi-dimensional arrays.
/// For example, "int[][*,*]" instead of "int[][,]" in C# or
/// "Integer()(*,*)" instead of "Integer()(*,*) in Visual Basic.
/// </summary>
UseAsterisksInMultiDimensionalArrays = 1 << 2,
/// <summary>
/// Displays "?" for erroneous types that lack names (perhaps due to faulty metadata).
/// </summary>
UseErrorTypeSymbolName = 1 << 3,
/// <summary>
/// Displays attributes names without the "Attribute" suffix, if possible.
/// </summary>
/// <remarks>
/// Has no effect outside <see cref="ISymbol.ToMinimalDisplayString"/> and only applies
/// if the context location is one where an attribute ca be referenced without the suffix.
/// </remarks>
RemoveAttributeSuffix = 1 << 4,
/// <summary>
/// Displays <see cref="Nullable{T}"/> as a normal generic type, rather than with
/// the special question mark syntax.
/// </summary>
ExpandNullable = 1 << 5,
/// <summary>
/// Append '?' to nullable reference types.
/// </summary>
IncludeNullableReferenceTypeModifier = 1 << 6,
/// <summary>
/// Allow the use of <c>default</c> instead of <c>default(T)</c> where applicable.
/// </summary>
AllowDefaultLiteral = 1 << 7,
/// <summary>
/// Append '!' to non-nullable reference types.
/// </summary>
IncludeNotNullableReferenceTypeModifier = 1 << 8,
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Implementation/TextBufferAssociatedViewService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
[Export(typeof(ITextViewConnectionListener))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
[Export(typeof(ITextBufferAssociatedViewService))]
internal class TextBufferAssociatedViewService : ITextViewConnectionListener, ITextBufferAssociatedViewService
{
#if DEBUG
private static readonly HashSet<ITextView> s_registeredViews = new();
#endif
private static readonly object s_gate = new();
private static readonly ConditionalWeakTable<ITextBuffer, HashSet<ITextView>> s_map =
new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TextBufferAssociatedViewService()
{
}
public event EventHandler<SubjectBuffersConnectedEventArgs> SubjectBuffersConnected;
void ITextViewConnectionListener.SubjectBuffersConnected(ITextView textView, ConnectionReason reason, IReadOnlyCollection<ITextBuffer> subjectBuffers)
{
lock (s_gate)
{
// only add roslyn type to tracking map
foreach (var buffer in subjectBuffers.Where(b => IsSupportedContentType(b.ContentType)))
{
if (!s_map.TryGetValue(buffer, out var set))
{
set = new HashSet<ITextView>();
s_map.Add(buffer, set);
}
set.Add(textView);
DebugRegisterView_NoLock(textView);
}
}
this.SubjectBuffersConnected?.Invoke(this, new SubjectBuffersConnectedEventArgs(textView, subjectBuffers.ToReadOnlyCollection()));
}
void ITextViewConnectionListener.SubjectBuffersDisconnected(ITextView textView, ConnectionReason reason, IReadOnlyCollection<ITextBuffer> subjectBuffers)
{
lock (s_gate)
{
// we need to check all buffers reported since we will be called after actual changes have happened.
// for example, if content type of a buffer changed, we will be called after it is changed, rather than before it.
foreach (var buffer in subjectBuffers)
{
if (s_map.TryGetValue(buffer, out var set))
{
set.Remove(textView);
if (set.Count == 0)
{
s_map.Remove(buffer);
}
}
}
}
}
private static bool IsSupportedContentType(IContentType contentType)
{
// This list should match the list of exported content types above
return contentType.IsOfType(ContentTypeNames.RoslynContentType) ||
contentType.IsOfType(ContentTypeNames.XamlContentType);
}
private static IList<ITextView> GetTextViews(ITextBuffer textBuffer)
{
lock (s_gate)
{
if (!s_map.TryGetValue(textBuffer, out var set))
{
return SpecializedCollections.EmptyList<ITextView>();
}
return set.ToList();
}
}
public IEnumerable<ITextView> GetAssociatedTextViews(ITextBuffer textBuffer)
=> GetTextViews(textBuffer);
private static bool HasFocus(ITextView textView)
=> textView.HasAggregateFocus;
public static bool AnyAssociatedViewHasFocus(ITextBuffer textBuffer)
{
if (textBuffer == null)
{
return false;
}
var views = GetTextViews(textBuffer);
if (views.Count == 0)
{
// We haven't seen the view yet. Assume it is visible.
return true;
}
return views.Any(HasFocus);
}
[Conditional("DEBUG")]
private static void DebugRegisterView_NoLock(ITextView textView)
{
#if DEBUG
if (s_registeredViews.Add(textView))
{
textView.Closed += OnTextViewClose;
}
#endif
}
#if DEBUG
private static void OnTextViewClose(object sender, EventArgs e)
{
var view = sender as ITextView;
lock (s_gate)
{
foreach (var buffer in view.BufferGraph.GetTextBuffers(b => IsSupportedContentType(b.ContentType)))
{
if (s_map.TryGetValue(buffer, out var set))
{
Contract.ThrowIfTrue(set.Contains(view));
}
}
s_registeredViews.Remove(view);
}
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
[Export(typeof(ITextViewConnectionListener))]
[ContentType(ContentTypeNames.RoslynContentType)]
[ContentType(ContentTypeNames.XamlContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
[Export(typeof(ITextBufferAssociatedViewService))]
internal class TextBufferAssociatedViewService : ITextViewConnectionListener, ITextBufferAssociatedViewService
{
#if DEBUG
private static readonly HashSet<ITextView> s_registeredViews = new();
#endif
private static readonly object s_gate = new();
private static readonly ConditionalWeakTable<ITextBuffer, HashSet<ITextView>> s_map =
new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TextBufferAssociatedViewService()
{
}
public event EventHandler<SubjectBuffersConnectedEventArgs> SubjectBuffersConnected;
void ITextViewConnectionListener.SubjectBuffersConnected(ITextView textView, ConnectionReason reason, IReadOnlyCollection<ITextBuffer> subjectBuffers)
{
lock (s_gate)
{
// only add roslyn type to tracking map
foreach (var buffer in subjectBuffers.Where(b => IsSupportedContentType(b.ContentType)))
{
if (!s_map.TryGetValue(buffer, out var set))
{
set = new HashSet<ITextView>();
s_map.Add(buffer, set);
}
set.Add(textView);
DebugRegisterView_NoLock(textView);
}
}
this.SubjectBuffersConnected?.Invoke(this, new SubjectBuffersConnectedEventArgs(textView, subjectBuffers.ToReadOnlyCollection()));
}
void ITextViewConnectionListener.SubjectBuffersDisconnected(ITextView textView, ConnectionReason reason, IReadOnlyCollection<ITextBuffer> subjectBuffers)
{
lock (s_gate)
{
// we need to check all buffers reported since we will be called after actual changes have happened.
// for example, if content type of a buffer changed, we will be called after it is changed, rather than before it.
foreach (var buffer in subjectBuffers)
{
if (s_map.TryGetValue(buffer, out var set))
{
set.Remove(textView);
if (set.Count == 0)
{
s_map.Remove(buffer);
}
}
}
}
}
private static bool IsSupportedContentType(IContentType contentType)
{
// This list should match the list of exported content types above
return contentType.IsOfType(ContentTypeNames.RoslynContentType) ||
contentType.IsOfType(ContentTypeNames.XamlContentType);
}
private static IList<ITextView> GetTextViews(ITextBuffer textBuffer)
{
lock (s_gate)
{
if (!s_map.TryGetValue(textBuffer, out var set))
{
return SpecializedCollections.EmptyList<ITextView>();
}
return set.ToList();
}
}
public IEnumerable<ITextView> GetAssociatedTextViews(ITextBuffer textBuffer)
=> GetTextViews(textBuffer);
private static bool HasFocus(ITextView textView)
=> textView.HasAggregateFocus;
public static bool AnyAssociatedViewHasFocus(ITextBuffer textBuffer)
{
if (textBuffer == null)
{
return false;
}
var views = GetTextViews(textBuffer);
if (views.Count == 0)
{
// We haven't seen the view yet. Assume it is visible.
return true;
}
return views.Any(HasFocus);
}
[Conditional("DEBUG")]
private static void DebugRegisterView_NoLock(ITextView textView)
{
#if DEBUG
if (s_registeredViews.Add(textView))
{
textView.Closed += OnTextViewClose;
}
#endif
}
#if DEBUG
private static void OnTextViewClose(object sender, EventArgs e)
{
var view = sender as ITextView;
lock (s_gate)
{
foreach (var buffer in view.BufferGraph.GetTextBuffers(b => IsSupportedContentType(b.ContentType)))
{
if (s_map.TryGetValue(buffer, out var set))
{
Contract.ThrowIfTrue(set.Contains(view));
}
}
s_registeredViews.Remove(view);
}
}
#endif
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.State_Parameter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private partial class State
{
private bool IsInParameterContext(
CancellationToken cancellationToken)
{
if (!_service.IsInParameterInitializer(Expression))
{
return false;
}
// The default value for a parameter is a constant. So we always allow it unless it
// happens to capture one of the method's type parameters.
var bindingMap = GetSemanticMap(cancellationToken);
if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>()
.Where(tp => tp.TypeParameterKind == TypeParameterKind.Method)
.Any())
{
return false;
}
return true;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private partial class State
{
private bool IsInParameterContext(
CancellationToken cancellationToken)
{
if (!_service.IsInParameterInitializer(Expression))
{
return false;
}
// The default value for a parameter is a constant. So we always allow it unless it
// happens to capture one of the method's type parameters.
var bindingMap = GetSemanticMap(cancellationToken);
if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>()
.Where(tp => tp.TypeParameterKind == TypeParameterKind.Method)
.Any())
{
return false;
}
return true;
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/CodeModel/NodeKeyValidation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal sealed class NodeKeyValidation
{
private readonly Dictionary<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>, List<GlobalNodeKey>> _nodeKeysMap =
new Dictionary<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>, List<GlobalNodeKey>>();
public NodeKeyValidation()
{
}
public NodeKeyValidation(ProjectCodeModelFactory projectCodeModelFactory)
{
foreach (var projectCodeModel in projectCodeModelFactory.GetAllProjectCodeModels())
{
var fcms = projectCodeModel.GetCachedFileCodeModelInstances();
foreach (var fcm in fcms)
{
var globalNodeKeys = fcm.Object.GetCurrentNodeKeys();
_nodeKeysMap.Add(fcm, globalNodeKeys);
}
}
}
public void AddFileCodeModel(FileCodeModel fileCodeModel)
{
var handle = new ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(fileCodeModel);
var globalNodeKeys = fileCodeModel.GetCurrentNodeKeys();
_nodeKeysMap.Add(handle, globalNodeKeys);
}
public void RestoreKeys()
{
foreach (var e in _nodeKeysMap)
{
e.Key.Object.ResetElementKeys(e.Value);
}
_nodeKeysMap.Clear();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal sealed class NodeKeyValidation
{
private readonly Dictionary<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>, List<GlobalNodeKey>> _nodeKeysMap =
new Dictionary<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>, List<GlobalNodeKey>>();
public NodeKeyValidation()
{
}
public NodeKeyValidation(ProjectCodeModelFactory projectCodeModelFactory)
{
foreach (var projectCodeModel in projectCodeModelFactory.GetAllProjectCodeModels())
{
var fcms = projectCodeModel.GetCachedFileCodeModelInstances();
foreach (var fcm in fcms)
{
var globalNodeKeys = fcm.Object.GetCurrentNodeKeys();
_nodeKeysMap.Add(fcm, globalNodeKeys);
}
}
}
public void AddFileCodeModel(FileCodeModel fileCodeModel)
{
var handle = new ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(fileCodeModel);
var globalNodeKeys = fileCodeModel.GetCurrentNodeKeys();
_nodeKeysMap.Add(handle, globalNodeKeys);
}
public void RestoreKeys()
{
foreach (var e in _nodeKeysMap)
{
e.Key.Object.ResetElementKeys(e.Value);
}
_nodeKeysMap.Clear();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/MemberDescriptor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.IO;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis.RuntimeMembers
{
[Flags()]
internal enum MemberFlags : byte
{
// BEGIN Mutually exclusive Member kinds:
Method = 0x01,
Field = 0x02,
Constructor = 0x04,
PropertyGet = 0x08,
Property = 0x10,
// END Mutually exclusive Member kinds
KindMask = 0x1F,
Static = 0x20,
Virtual = 0x40, // Virtual in CLR terms, i.e. sealed should be accepted.
}
/// <summary>
/// Structure that describes a member of a type.
/// </summary>
internal readonly struct MemberDescriptor
{
public readonly MemberFlags Flags;
/// <summary>
/// Id/token of containing type, usually value from some enum.
/// For example from SpecialType enum.
/// I am not using SpecialType as the type for this field because
/// VB runtime types are not part of SpecialType.
///
/// So, the implication is that any type ids we use outside of the SpecialType
/// (either for the VB runtime classes, or types like System.Task etc.) will need
/// to use IDs that are all mutually disjoint.
/// </summary>
public readonly short DeclaringTypeId;
public string? DeclaringTypeMetadataName
{
get
{
return DeclaringTypeId <= (int)SpecialType.Count
? ((SpecialType)DeclaringTypeId).GetMetadataName()
: ((WellKnownType)DeclaringTypeId).GetMetadataName();
}
}
public readonly ushort Arity;
public readonly string Name;
/// <summary>
/// Signature of the field or method, similar to metadata signature,
/// but with the following exceptions:
/// 1) Truncated on the left, for methods starts at [ParamCount], for fields at [Type]
/// 2) Type tokens are not compressed
/// 3) BOOLEAN | CHAR | I1 | U1 | I2 | U2 | I4 | U4 | I8 | U8 | R4 | R8 | I | U | Void types are encoded by
/// using VALUETYPE+typeId notation.
/// 4) array bounds are not included.
/// 5) modifiers are not included.
/// 6) (CLASS | VALUETYPE) are omitted after GENERICINST
/// </summary>
public readonly ImmutableArray<byte> Signature;
/// <summary>
/// Applicable only to properties and methods, throws otherwise.
/// </summary>
public int ParametersCount
{
get
{
MemberFlags memberKind = Flags & MemberFlags.KindMask;
switch (memberKind)
{
case MemberFlags.Constructor:
case MemberFlags.Method:
case MemberFlags.PropertyGet:
case MemberFlags.Property:
return Signature[0];
default:
throw ExceptionUtilities.UnexpectedValue(memberKind);
}
}
}
public MemberDescriptor(
MemberFlags Flags,
short DeclaringTypeId,
string Name,
ImmutableArray<byte> Signature,
ushort Arity = 0)
{
this.Flags = Flags;
this.DeclaringTypeId = DeclaringTypeId;
this.Name = Name;
this.Arity = Arity;
this.Signature = Signature;
}
internal static ImmutableArray<MemberDescriptor> InitializeFromStream(Stream stream, string[] nameTable)
{
int count = nameTable.Length;
var builder = ImmutableArray.CreateBuilder<MemberDescriptor>(count);
var signatureBuilder = ImmutableArray.CreateBuilder<byte>();
for (int i = 0; i < count; i++)
{
MemberFlags flags = (MemberFlags)stream.ReadByte();
short declaringTypeId = ReadTypeId(stream);
ushort arity = (ushort)stream.ReadByte();
if ((flags & MemberFlags.Field) != 0)
{
ParseType(signatureBuilder, stream);
}
else
{
// Property, PropertyGet, Method or Constructor
ParseMethodOrPropertySignature(signatureBuilder, stream);
}
builder.Add(new MemberDescriptor(flags, declaringTypeId, nameTable[i], signatureBuilder.ToImmutable(), arity));
signatureBuilder.Clear();
}
return builder.ToImmutable();
}
/// <summary>
/// The type Id may be:
/// (1) encoded in a single byte (for types below 255)
/// (2) encoded in two bytes (255 + extension byte) for types below 512
/// </summary>
private static short ReadTypeId(Stream stream)
{
var firstByte = (byte)stream.ReadByte();
if (firstByte == (byte)WellKnownType.ExtSentinel)
{
return (short)(stream.ReadByte() + WellKnownType.ExtSentinel);
}
else
{
return firstByte;
}
}
private static void ParseMethodOrPropertySignature(ImmutableArray<byte>.Builder builder, Stream stream)
{
int paramCount = stream.ReadByte();
builder.Add((byte)paramCount);
// Return type
ParseType(builder, stream, allowByRef: true);
// Parameters
for (int i = 0; i < paramCount; i++)
{
ParseType(builder, stream, allowByRef: true);
}
}
private static void ParseType(ImmutableArray<byte>.Builder builder, Stream stream, bool allowByRef = false)
{
while (true)
{
var typeCode = (SignatureTypeCode)stream.ReadByte();
builder.Add((byte)typeCode);
switch (typeCode)
{
default:
throw ExceptionUtilities.UnexpectedValue(typeCode);
case SignatureTypeCode.TypeHandle:
ParseTypeHandle(builder, stream);
return;
case SignatureTypeCode.GenericTypeParameter:
case SignatureTypeCode.GenericMethodParameter:
builder.Add((byte)stream.ReadByte());
return;
case SignatureTypeCode.ByReference:
if (!allowByRef) goto default;
break;
case SignatureTypeCode.SZArray:
break;
case SignatureTypeCode.Pointer:
break;
case SignatureTypeCode.GenericTypeInstance:
ParseGenericTypeInstance(builder, stream);
return;
}
allowByRef = false;
}
}
/// <summary>
/// Read a type Id from the stream and copy it into the builder.
/// This may copy one or two bytes depending on the first one.
/// </summary>
private static void ParseTypeHandle(ImmutableArray<byte>.Builder builder, Stream stream)
{
var firstByte = (byte)stream.ReadByte();
builder.Add(firstByte);
if (firstByte == (byte)WellKnownType.ExtSentinel)
{
var secondByte = (byte)stream.ReadByte();
builder.Add(secondByte);
}
}
private static void ParseGenericTypeInstance(ImmutableArray<byte>.Builder builder, Stream stream)
{
ParseType(builder, stream);
// Generic type parameters
int argumentCount = stream.ReadByte();
builder.Add((byte)argumentCount);
for (int i = 0; i < argumentCount; i++)
{
ParseType(builder, stream);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.IO;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis.RuntimeMembers
{
[Flags()]
internal enum MemberFlags : byte
{
// BEGIN Mutually exclusive Member kinds:
Method = 0x01,
Field = 0x02,
Constructor = 0x04,
PropertyGet = 0x08,
Property = 0x10,
// END Mutually exclusive Member kinds
KindMask = 0x1F,
Static = 0x20,
Virtual = 0x40, // Virtual in CLR terms, i.e. sealed should be accepted.
}
/// <summary>
/// Structure that describes a member of a type.
/// </summary>
internal readonly struct MemberDescriptor
{
public readonly MemberFlags Flags;
/// <summary>
/// Id/token of containing type, usually value from some enum.
/// For example from SpecialType enum.
/// I am not using SpecialType as the type for this field because
/// VB runtime types are not part of SpecialType.
///
/// So, the implication is that any type ids we use outside of the SpecialType
/// (either for the VB runtime classes, or types like System.Task etc.) will need
/// to use IDs that are all mutually disjoint.
/// </summary>
public readonly short DeclaringTypeId;
public string? DeclaringTypeMetadataName
{
get
{
return DeclaringTypeId <= (int)SpecialType.Count
? ((SpecialType)DeclaringTypeId).GetMetadataName()
: ((WellKnownType)DeclaringTypeId).GetMetadataName();
}
}
public readonly ushort Arity;
public readonly string Name;
/// <summary>
/// Signature of the field or method, similar to metadata signature,
/// but with the following exceptions:
/// 1) Truncated on the left, for methods starts at [ParamCount], for fields at [Type]
/// 2) Type tokens are not compressed
/// 3) BOOLEAN | CHAR | I1 | U1 | I2 | U2 | I4 | U4 | I8 | U8 | R4 | R8 | I | U | Void types are encoded by
/// using VALUETYPE+typeId notation.
/// 4) array bounds are not included.
/// 5) modifiers are not included.
/// 6) (CLASS | VALUETYPE) are omitted after GENERICINST
/// </summary>
public readonly ImmutableArray<byte> Signature;
/// <summary>
/// Applicable only to properties and methods, throws otherwise.
/// </summary>
public int ParametersCount
{
get
{
MemberFlags memberKind = Flags & MemberFlags.KindMask;
switch (memberKind)
{
case MemberFlags.Constructor:
case MemberFlags.Method:
case MemberFlags.PropertyGet:
case MemberFlags.Property:
return Signature[0];
default:
throw ExceptionUtilities.UnexpectedValue(memberKind);
}
}
}
public MemberDescriptor(
MemberFlags Flags,
short DeclaringTypeId,
string Name,
ImmutableArray<byte> Signature,
ushort Arity = 0)
{
this.Flags = Flags;
this.DeclaringTypeId = DeclaringTypeId;
this.Name = Name;
this.Arity = Arity;
this.Signature = Signature;
}
internal static ImmutableArray<MemberDescriptor> InitializeFromStream(Stream stream, string[] nameTable)
{
int count = nameTable.Length;
var builder = ImmutableArray.CreateBuilder<MemberDescriptor>(count);
var signatureBuilder = ImmutableArray.CreateBuilder<byte>();
for (int i = 0; i < count; i++)
{
MemberFlags flags = (MemberFlags)stream.ReadByte();
short declaringTypeId = ReadTypeId(stream);
ushort arity = (ushort)stream.ReadByte();
if ((flags & MemberFlags.Field) != 0)
{
ParseType(signatureBuilder, stream);
}
else
{
// Property, PropertyGet, Method or Constructor
ParseMethodOrPropertySignature(signatureBuilder, stream);
}
builder.Add(new MemberDescriptor(flags, declaringTypeId, nameTable[i], signatureBuilder.ToImmutable(), arity));
signatureBuilder.Clear();
}
return builder.ToImmutable();
}
/// <summary>
/// The type Id may be:
/// (1) encoded in a single byte (for types below 255)
/// (2) encoded in two bytes (255 + extension byte) for types below 512
/// </summary>
private static short ReadTypeId(Stream stream)
{
var firstByte = (byte)stream.ReadByte();
if (firstByte == (byte)WellKnownType.ExtSentinel)
{
return (short)(stream.ReadByte() + WellKnownType.ExtSentinel);
}
else
{
return firstByte;
}
}
private static void ParseMethodOrPropertySignature(ImmutableArray<byte>.Builder builder, Stream stream)
{
int paramCount = stream.ReadByte();
builder.Add((byte)paramCount);
// Return type
ParseType(builder, stream, allowByRef: true);
// Parameters
for (int i = 0; i < paramCount; i++)
{
ParseType(builder, stream, allowByRef: true);
}
}
private static void ParseType(ImmutableArray<byte>.Builder builder, Stream stream, bool allowByRef = false)
{
while (true)
{
var typeCode = (SignatureTypeCode)stream.ReadByte();
builder.Add((byte)typeCode);
switch (typeCode)
{
default:
throw ExceptionUtilities.UnexpectedValue(typeCode);
case SignatureTypeCode.TypeHandle:
ParseTypeHandle(builder, stream);
return;
case SignatureTypeCode.GenericTypeParameter:
case SignatureTypeCode.GenericMethodParameter:
builder.Add((byte)stream.ReadByte());
return;
case SignatureTypeCode.ByReference:
if (!allowByRef) goto default;
break;
case SignatureTypeCode.SZArray:
break;
case SignatureTypeCode.Pointer:
break;
case SignatureTypeCode.GenericTypeInstance:
ParseGenericTypeInstance(builder, stream);
return;
}
allowByRef = false;
}
}
/// <summary>
/// Read a type Id from the stream and copy it into the builder.
/// This may copy one or two bytes depending on the first one.
/// </summary>
private static void ParseTypeHandle(ImmutableArray<byte>.Builder builder, Stream stream)
{
var firstByte = (byte)stream.ReadByte();
builder.Add(firstByte);
if (firstByte == (byte)WellKnownType.ExtSentinel)
{
var secondByte = (byte)stream.ReadByte();
builder.Add(secondByte);
}
}
private static void ParseGenericTypeInstance(ImmutableArray<byte>.Builder builder, Stream stream)
{
ParseType(builder, stream);
// Generic type parameters
int argumentCount = stream.ReadByte();
builder.Add((byte)argumentCount);
for (int i = 0; i < argumentCount; i++)
{
ParseType(builder, stream);
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/OperatorOverloadSyntaxClassifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Classification
{
internal class OperatorOverloadSyntaxClassifier : AbstractSyntaxClassifier
{
public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(
typeof(AssignmentExpressionSyntax),
typeof(BinaryExpressionSyntax),
typeof(PrefixUnaryExpressionSyntax),
typeof(PostfixUnaryExpressionSyntax));
public override void AddClassifications(
Workspace workspace,
SyntaxNode syntax,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
var symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken);
if (symbolInfo.Symbol is IMethodSymbol methodSymbol
&& methodSymbol.MethodKind == MethodKind.UserDefinedOperator)
{
var operatorSpan = GetOperatorTokenSpan(syntax);
if (!operatorSpan.IsEmpty)
{
result.Add(new ClassifiedSpan(operatorSpan, ClassificationTypeNames.OperatorOverloaded));
}
}
}
private static TextSpan GetOperatorTokenSpan(SyntaxNode syntax)
=> syntax switch
{
AssignmentExpressionSyntax assignmentExpression => assignmentExpression.OperatorToken.Span,
BinaryExpressionSyntax binaryExpression => binaryExpression.OperatorToken.Span,
PrefixUnaryExpressionSyntax prefixUnaryExpression => prefixUnaryExpression.OperatorToken.Span,
PostfixUnaryExpressionSyntax postfixUnaryExpression => postfixUnaryExpression.OperatorToken.Span,
_ => default,
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Classification
{
internal class OperatorOverloadSyntaxClassifier : AbstractSyntaxClassifier
{
public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(
typeof(AssignmentExpressionSyntax),
typeof(BinaryExpressionSyntax),
typeof(PrefixUnaryExpressionSyntax),
typeof(PostfixUnaryExpressionSyntax));
public override void AddClassifications(
Workspace workspace,
SyntaxNode syntax,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
var symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken);
if (symbolInfo.Symbol is IMethodSymbol methodSymbol
&& methodSymbol.MethodKind == MethodKind.UserDefinedOperator)
{
var operatorSpan = GetOperatorTokenSpan(syntax);
if (!operatorSpan.IsEmpty)
{
result.Add(new ClassifiedSpan(operatorSpan, ClassificationTypeNames.OperatorOverloaded));
}
}
}
private static TextSpan GetOperatorTokenSpan(SyntaxNode syntax)
=> syntax switch
{
AssignmentExpressionSyntax assignmentExpression => assignmentExpression.OperatorToken.Span,
BinaryExpressionSyntax binaryExpression => binaryExpression.OperatorToken.Span,
PrefixUnaryExpressionSyntax prefixUnaryExpression => prefixUnaryExpression.OperatorToken.Span,
PostfixUnaryExpressionSyntax postfixUnaryExpression => postfixUnaryExpression.OperatorToken.Span,
_ => default,
};
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Emit/PDB/PortablePdbTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PortablePdbTests : CSharpPDBTestBase
{
[Fact]
public void SequencePointBlob()
{
string source = @"
class C
{
public static void Main()
{
if (F())
{
System.Console.WriteLine(1);
}
}
public static bool F() => false;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);
using (var peReader = new PEReader(peBlob))
using (var pdbMetadata = new PinnedMetadata(pdbStream.ToImmutable()))
{
var mdReader = peReader.GetMetadataReader();
var pdbReader = pdbMetadata.Reader;
foreach (var methodHandle in mdReader.MethodDefinitions)
{
var method = mdReader.GetMethodDefinition(methodHandle);
var methodDebugInfo = pdbReader.GetMethodDebugInformation(methodHandle);
var name = mdReader.GetString(method.Name);
TextWriter writer = new StringWriter();
foreach (var sp in methodDebugInfo.GetSequencePoints())
{
if (sp.IsHidden)
{
writer.WriteLine($"{sp.Offset}: <hidden>");
}
else
{
writer.WriteLine($"{sp.Offset}: ({sp.StartLine},{sp.StartColumn})-({sp.EndLine},{sp.EndColumn})");
}
}
var spString = writer.ToString();
var spBlob = pdbReader.GetBlobBytes(methodDebugInfo.SequencePointsBlob);
switch (name)
{
case "Main":
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
0: (5,5)-(5,6)
1: (6,9)-(6,17)
7: <hidden>
10: (7,9)-(7,10)
11: (8,13)-(8,41)
18: (9,9)-(9,10)
19: (10,5)-(10,6)
", spString);
AssertEx.Equal(new byte[]
{
0x01, // local signature
0x00, // IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x05, // Start Line
0x05, // Start Column
0x01, // delta IL offset
0x00, // Delta Lines
0x08, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x06, // delta IL offset
0x00, // hidden
0x00, // hidden
0x03, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x00, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x1C, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x07, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
}, spBlob);
break;
case "F":
AssertEx.AssertEqualToleratingWhitespaceDifferences("0: (12,31)-(12,36)", spString);
AssertEx.Equal(new byte[]
{
0x00, // local signature
0x00, // delta IL offset
0x00, // Delta Lines
0x05, // Delta Columns
0x0C, // Start Line
0x1F // Start Column
}, spBlob);
break;
}
}
}
}
[Fact]
public void EmbeddedPortablePdb()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbFilePath(@"a/b/c/d.pdb").
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA512));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var embedded = entries[2];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA512", checksumData.AlgorithmName);
Assert.Equal(64, checksumData.Checksum.Length);
}
}
[Fact]
public void EmbeddedPortablePdb_Deterministic()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll.WithDeterministic(true));
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA384).
WithPdbFilePath(@"a/b/c/d.pdb"));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var reproducible = entries[2];
var embedded = entries[3];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA384", checksumData.AlgorithmName);
Assert.Equal(48, checksumData.Checksum.Length);
// Reproducible entry:
Assert.Equal(0, reproducible.MajorVersion);
Assert.Equal(0, reproducible.MinorVersion);
Assert.Equal(0U, reproducible.Stamp);
Assert.Equal(0, reproducible.DataSize);
}
}
[Fact]
public void SourceLink()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream, sourceLinkStream: new MemoryStream(sourceLinkBlob));
pdbStream.Position = 0;
using (var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream))
{
var pdbReader = provider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
[Fact]
public void SourceLink_Embedded()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded), sourceLinkStream: new MemoryStream(sourceLinkBlob));
using (var peReader = new PEReader(peBlob))
{
var embeddedEntry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry))
{
var pdbReader = embeddedMetadataProvider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
}
[Fact]
public void SourceLink_Errors()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkStream = new TestStream(canRead: true, readFunc: (_, __, ___) => { throw new Exception("Error!"); });
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var result = c.Emit(new MemoryStream(), new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: sourceLinkStream);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Error!'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("Error!").WithLocation(1, 1));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PortablePdbTests : CSharpPDBTestBase
{
[Fact]
public void SequencePointBlob()
{
string source = @"
class C
{
public static void Main()
{
if (F())
{
System.Console.WriteLine(1);
}
}
public static bool F() => false;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);
using (var peReader = new PEReader(peBlob))
using (var pdbMetadata = new PinnedMetadata(pdbStream.ToImmutable()))
{
var mdReader = peReader.GetMetadataReader();
var pdbReader = pdbMetadata.Reader;
foreach (var methodHandle in mdReader.MethodDefinitions)
{
var method = mdReader.GetMethodDefinition(methodHandle);
var methodDebugInfo = pdbReader.GetMethodDebugInformation(methodHandle);
var name = mdReader.GetString(method.Name);
TextWriter writer = new StringWriter();
foreach (var sp in methodDebugInfo.GetSequencePoints())
{
if (sp.IsHidden)
{
writer.WriteLine($"{sp.Offset}: <hidden>");
}
else
{
writer.WriteLine($"{sp.Offset}: ({sp.StartLine},{sp.StartColumn})-({sp.EndLine},{sp.EndColumn})");
}
}
var spString = writer.ToString();
var spBlob = pdbReader.GetBlobBytes(methodDebugInfo.SequencePointsBlob);
switch (name)
{
case "Main":
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
0: (5,5)-(5,6)
1: (6,9)-(6,17)
7: <hidden>
10: (7,9)-(7,10)
11: (8,13)-(8,41)
18: (9,9)-(9,10)
19: (10,5)-(10,6)
", spString);
AssertEx.Equal(new byte[]
{
0x01, // local signature
0x00, // IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x05, // Start Line
0x05, // Start Column
0x01, // delta IL offset
0x00, // Delta Lines
0x08, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x06, // delta IL offset
0x00, // hidden
0x00, // hidden
0x03, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x00, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x1C, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x07, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
}, spBlob);
break;
case "F":
AssertEx.AssertEqualToleratingWhitespaceDifferences("0: (12,31)-(12,36)", spString);
AssertEx.Equal(new byte[]
{
0x00, // local signature
0x00, // delta IL offset
0x00, // Delta Lines
0x05, // Delta Columns
0x0C, // Start Line
0x1F // Start Column
}, spBlob);
break;
}
}
}
}
[Fact]
public void EmbeddedPortablePdb()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbFilePath(@"a/b/c/d.pdb").
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA512));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var embedded = entries[2];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA512", checksumData.AlgorithmName);
Assert.Equal(64, checksumData.Checksum.Length);
}
}
[Fact]
public void EmbeddedPortablePdb_Deterministic()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll.WithDeterministic(true));
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA384).
WithPdbFilePath(@"a/b/c/d.pdb"));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var reproducible = entries[2];
var embedded = entries[3];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA384", checksumData.AlgorithmName);
Assert.Equal(48, checksumData.Checksum.Length);
// Reproducible entry:
Assert.Equal(0, reproducible.MajorVersion);
Assert.Equal(0, reproducible.MinorVersion);
Assert.Equal(0U, reproducible.Stamp);
Assert.Equal(0, reproducible.DataSize);
}
}
[Fact]
public void SourceLink()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream, sourceLinkStream: new MemoryStream(sourceLinkBlob));
pdbStream.Position = 0;
using (var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream))
{
var pdbReader = provider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
[Fact]
public void SourceLink_Embedded()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded), sourceLinkStream: new MemoryStream(sourceLinkBlob));
using (var peReader = new PEReader(peBlob))
{
var embeddedEntry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry))
{
var pdbReader = embeddedMetadataProvider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
}
[Fact]
public void SourceLink_Errors()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkStream = new TestStream(canRead: true, readFunc: (_, __, ___) => { throw new Exception("Error!"); });
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var result = c.Emit(new MemoryStream(), new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: sourceLinkStream);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Error!'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("Error!").WithLocation(1, 1));
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Core/Diagnostics/DiagnosticsHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public static class DiagnosticsHelper
{
private static TextSpan FindSpan(string source, string pattern)
{
var match = Regex.Match(source, pattern);
Assert.True(match.Success, "Could not find a match for \"" + pattern + "\" in:" + Environment.NewLine + source);
return new TextSpan(match.Index, match.Length);
}
private static void VerifyDiagnostics(IEnumerable<Diagnostic> actualDiagnostics, params string[] expectedDiagnosticIds)
{
var actualDiagnosticIds = actualDiagnostics.Select(d => d.Id);
Assert.True(expectedDiagnosticIds.SequenceEqual(actualDiagnosticIds),
Environment.NewLine + "Expected: " + string.Join(", ", expectedDiagnosticIds) +
Environment.NewLine + "Actual: " + string.Join(", ", actualDiagnosticIds));
}
public static void VerifyDiagnostics(SemanticModel model, string source, string pattern, params string[] expectedDiagnosticIds)
{
VerifyDiagnostics(model.GetDiagnostics(FindSpan(source, pattern)), expectedDiagnosticIds);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public static class DiagnosticsHelper
{
private static TextSpan FindSpan(string source, string pattern)
{
var match = Regex.Match(source, pattern);
Assert.True(match.Success, "Could not find a match for \"" + pattern + "\" in:" + Environment.NewLine + source);
return new TextSpan(match.Index, match.Length);
}
private static void VerifyDiagnostics(IEnumerable<Diagnostic> actualDiagnostics, params string[] expectedDiagnosticIds)
{
var actualDiagnosticIds = actualDiagnostics.Select(d => d.Id);
Assert.True(expectedDiagnosticIds.SequenceEqual(actualDiagnosticIds),
Environment.NewLine + "Expected: " + string.Join(", ", expectedDiagnosticIds) +
Environment.NewLine + "Actual: " + string.Join(", ", actualDiagnosticIds));
}
public static void VerifyDiagnostics(SemanticModel model, string source, string pattern, params string[] expectedDiagnosticIds)
{
VerifyDiagnostics(model.GetDiagnostics(FindSpan(source, pattern)), expectedDiagnosticIds);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_StringConcat.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// The strategy of this rewrite is to do rewrite "locally".
/// We analyze arguments of the concat in a shallow fashion assuming that
/// lowering and optimizations (including this one) is already done for the arguments.
/// Based on the arguments we select the most appropriate pattern for the current node.
///
/// NOTE: it is not guaranteed that the node that we chose will be the most optimal since we have only
/// local information - i.e. we look at the arguments, but we do not know about siblings.
/// When we move to the parent, the node may be rewritten by this or some another optimization.
///
/// Example:
/// result = ( "abc" + "def" + null ?? expr1 + "moo" + "baz" ) + expr2
///
/// Will rewrite into:
/// result = Concat("abcdef", expr2)
///
/// However there will be transient nodes like Concat(expr1 + "moo") that will not be present in the
/// resulting tree.
///
/// </summary>
private BoundExpression RewriteStringConcatenation(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type)
{
Debug.Assert(
operatorKind == BinaryOperatorKind.StringConcatenation ||
operatorKind == BinaryOperatorKind.StringAndObjectConcatenation ||
operatorKind == BinaryOperatorKind.ObjectAndStringConcatenation);
if (_inExpressionLambda)
{
return RewriteStringConcatInExpressionLambda(syntax, operatorKind, loweredLeft, loweredRight, type);
}
// Convert both sides to a string (calling ToString if necessary)
loweredLeft = ConvertConcatExprToString(syntax, loweredLeft);
loweredRight = ConvertConcatExprToString(syntax, loweredRight);
Debug.Assert(loweredLeft.Type is { } && (loweredLeft.Type.IsStringType() || loweredLeft.Type.IsErrorType()) || loweredLeft.ConstantValue?.IsNull == true);
Debug.Assert(loweredRight.Type is { } && (loweredRight.Type.IsStringType() || loweredRight.Type.IsErrorType()) || loweredRight.ConstantValue?.IsNull == true);
// try fold two args without flattening.
var folded = TryFoldTwoConcatOperands(syntax, loweredLeft, loweredRight);
if (folded != null)
{
return folded;
}
// flatten and merge - ( expr1 + "A" ) + ("B" + expr2) ===> (expr1 + "AB" + expr2)
ArrayBuilder<BoundExpression> leftFlattened = ArrayBuilder<BoundExpression>.GetInstance();
ArrayBuilder<BoundExpression> rightFlattened = ArrayBuilder<BoundExpression>.GetInstance();
FlattenConcatArg(loweredLeft, leftFlattened);
FlattenConcatArg(loweredRight, rightFlattened);
if (leftFlattened.Any() && rightFlattened.Any())
{
folded = TryFoldTwoConcatOperands(syntax, leftFlattened.Last(), rightFlattened.First());
if (folded != null)
{
rightFlattened[0] = folded;
leftFlattened.RemoveLast();
}
}
leftFlattened.AddRange(rightFlattened);
rightFlattened.Free();
BoundExpression result;
switch (leftFlattened.Count)
{
case 0:
result = _factory.StringLiteral(string.Empty);
break;
case 1:
// All code paths which reach here (through TryFoldTwoConcatOperands) have already called
// RewriteStringConcatenationOneExpr if necessary
result = leftFlattened[0];
break;
case 2:
var left = leftFlattened[0];
var right = leftFlattened[1];
result = RewriteStringConcatenationTwoExprs(syntax, left, right);
break;
case 3:
{
var first = leftFlattened[0];
var second = leftFlattened[1];
var third = leftFlattened[2];
result = RewriteStringConcatenationThreeExprs(syntax, first, second, third);
}
break;
case 4:
{
var first = leftFlattened[0];
var second = leftFlattened[1];
var third = leftFlattened[2];
var fourth = leftFlattened[3];
result = RewriteStringConcatenationFourExprs(syntax, first, second, third, fourth);
}
break;
default:
result = RewriteStringConcatenationManyExprs(syntax, leftFlattened.ToImmutable());
break;
}
leftFlattened.Free();
return result;
}
/// <summary>
/// digs into known concat operators and unwraps their arguments
/// otherwise returns the expression as-is
///
/// Generally we only need to recognize same node patterns that we create as a result of concatenation rewrite.
/// </summary>
private void FlattenConcatArg(BoundExpression lowered, ArrayBuilder<BoundExpression> flattened)
{
if (TryExtractStringConcatArgs(lowered, out var arguments))
{
flattened.AddRange(arguments);
}
else
{
// fallback - if nothing above worked, leave arg as-is
flattened.Add(lowered);
}
}
/// <summary>
/// Determines whether an expression is a known string concat operator (with or without a subsequent ?? ""), and extracts
/// its args if so.
/// </summary>
/// <returns>True if this is a call to a known string concat operator, false otherwise</returns>
private bool TryExtractStringConcatArgs(BoundExpression lowered, out ImmutableArray<BoundExpression> arguments)
{
switch (lowered.Kind)
{
case BoundKind.Call:
var boundCall = (BoundCall)lowered;
var method = boundCall.Method;
if (method.IsStatic && method.ContainingType.SpecialType == SpecialType.System_String)
{
if ((object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString) ||
(object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringString) ||
(object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringStringString))
{
arguments = boundCall.Arguments;
return true;
}
if ((object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringArray))
{
var args = boundCall.Arguments[0] as BoundArrayCreation;
if (args != null)
{
var initializer = args.InitializerOpt;
if (initializer != null)
{
arguments = initializer.Initializers;
return true;
}
}
}
}
break;
case BoundKind.NullCoalescingOperator:
var boundCoalesce = (BoundNullCoalescingOperator)lowered;
if (boundCoalesce.LeftConversion.IsIdentity)
{
// The RHS may be a constant value with an identity conversion to string even
// if it is not a string: in particular, the null literal behaves this way.
// To be safe, check that the constant value is actually a string before
// attempting to access its value as a string.
var rightConstant = boundCoalesce.RightOperand.ConstantValue;
if (rightConstant != null && rightConstant.IsString && rightConstant.StringValue.Length == 0)
{
arguments = ImmutableArray.Create(boundCoalesce.LeftOperand);
return true;
}
}
break;
}
arguments = default;
return false;
}
/// <summary>
/// folds two concat operands into one expression if possible
/// otherwise returns null
/// </summary>
private BoundExpression? TryFoldTwoConcatOperands(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight)
{
// both left and right are constants
var leftConst = loweredLeft.ConstantValue;
var rightConst = loweredRight.ConstantValue;
if (leftConst != null && rightConst != null)
{
// const concat may fail to fold if strings are huge.
// This would be unusual.
ConstantValue? concatenated = TryFoldTwoConcatConsts(leftConst, rightConst);
if (concatenated != null)
{
return _factory.StringLiteral(concatenated);
}
}
// one or another is null.
if (IsNullOrEmptyStringConstant(loweredLeft))
{
if (IsNullOrEmptyStringConstant(loweredRight))
{
return _factory.Literal(string.Empty);
}
return RewriteStringConcatenationOneExpr(syntax, loweredRight);
}
else if (IsNullOrEmptyStringConstant(loweredRight))
{
return RewriteStringConcatenationOneExpr(syntax, loweredLeft);
}
return null;
}
private static bool IsNullOrEmptyStringConstant(BoundExpression operand)
{
return (operand.ConstantValue != null && string.IsNullOrEmpty(operand.ConstantValue.StringValue)) ||
operand.IsDefaultValue();
}
/// <summary>
/// folds two concat constants into one if possible
/// otherwise returns null.
/// It is generally always possible to concat constants, unless resulting string would be too large.
/// </summary>
private static ConstantValue? TryFoldTwoConcatConsts(ConstantValue leftConst, ConstantValue rightConst)
{
var leftVal = leftConst.StringValue;
var rightVal = rightConst.StringValue;
if (!leftConst.IsDefaultValue && !rightConst.IsDefaultValue)
{
Debug.Assert(leftVal is { } && rightVal is { });
if (leftVal.Length + rightVal.Length < 0)
{
return null;
}
}
// TODO: if transient string allocations are an issue, consider introducing constants that contain builders.
// it may be not so easy to even get here though, since typical
// "A" + "B" + "C" + ... cases should be folded in the binder as spec requires so.
// we would be mostly picking here edge cases like "A" + (object)null + "B" + (object)null + ...
return ConstantValue.Create(leftVal + rightVal);
}
/// <summary>
/// Strangely enough there is such a thing as unary concatenation and it must be rewritten.
/// </summary>
private BoundExpression RewriteStringConcatenationOneExpr(SyntaxNode syntax, BoundExpression loweredOperand)
{
// If it's a call to 'string.Concat' (or is something which ends in '?? ""', which this method also extracts),
// we know the result cannot be null. Otherwise return loweredOperand ?? ""
if (TryExtractStringConcatArgs(loweredOperand, out _))
{
return loweredOperand;
}
else
{
return _factory.Coalesce(loweredOperand, _factory.Literal(""));
}
}
private BoundExpression RewriteStringConcatenationTwoExprs(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight)
{
Debug.Assert(loweredLeft.HasAnyErrors || loweredLeft.Type is { } && loweredLeft.Type.IsStringType());
Debug.Assert(loweredRight.HasAnyErrors || loweredRight.Type is { } && loweredRight.Type.IsStringType());
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringString);
Debug.Assert((object)method != null);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight);
}
private BoundExpression RewriteStringConcatenationThreeExprs(SyntaxNode syntax, BoundExpression loweredFirst, BoundExpression loweredSecond, BoundExpression loweredThird)
{
Debug.Assert(loweredFirst.HasAnyErrors || loweredFirst.Type is { } && loweredFirst.Type.IsStringType());
Debug.Assert(loweredSecond.HasAnyErrors || loweredSecond.Type is { } && loweredSecond.Type.IsStringType());
Debug.Assert(loweredThird.HasAnyErrors || loweredThird.Type is { } && loweredThird.Type.IsStringType());
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringStringString);
Debug.Assert((object)method != null);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, ImmutableArray.Create(loweredFirst, loweredSecond, loweredThird));
}
private BoundExpression RewriteStringConcatenationFourExprs(SyntaxNode syntax, BoundExpression loweredFirst, BoundExpression loweredSecond, BoundExpression loweredThird, BoundExpression loweredFourth)
{
Debug.Assert(loweredFirst.HasAnyErrors || loweredFirst.Type is { } && loweredFirst.Type.IsStringType());
Debug.Assert(loweredSecond.HasAnyErrors || loweredSecond.Type is { } && loweredSecond.Type.IsStringType());
Debug.Assert(loweredThird.HasAnyErrors || loweredThird.Type is { } && loweredThird.Type.IsStringType());
Debug.Assert(loweredFourth.HasAnyErrors || loweredFourth.Type is { } && loweredFourth.Type.IsStringType());
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringStringStringString);
Debug.Assert((object)method != null);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, ImmutableArray.Create(loweredFirst, loweredSecond, loweredThird, loweredFourth));
}
private BoundExpression RewriteStringConcatenationManyExprs(SyntaxNode syntax, ImmutableArray<BoundExpression> loweredArgs)
{
Debug.Assert(loweredArgs.Length > 4);
Debug.Assert(loweredArgs.All(a => a.HasErrors || a.Type is { } && a.Type.IsStringType()));
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringArray);
Debug.Assert((object)method != null);
var array = _factory.ArrayOrEmpty(_factory.SpecialType(SpecialType.System_String), loweredArgs);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, array);
}
/// <summary>
/// Most of the above optimizations are not applicable in expression trees as the operator
/// must stay a binary operator. We cannot do much beyond constant folding which is done in binder.
/// </summary>
private BoundExpression RewriteStringConcatInExpressionLambda(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type)
{
SpecialMember member = (operatorKind == BinaryOperatorKind.StringConcatenation) ?
SpecialMember.System_String__ConcatStringString :
SpecialMember.System_String__ConcatObjectObject;
var method = UnsafeGetSpecialTypeMethod(syntax, member);
Debug.Assert((object)method != null);
return new BoundBinaryOperator(syntax, operatorKind, constantValueOpt: null, method, constrainedToTypeOpt: null, default(LookupResultKind), loweredLeft, loweredRight, type);
}
/// <summary>
/// Returns an expression which converts the given expression into a string (or null).
/// If necessary, this invokes .ToString() on the expression, to avoid boxing value types.
/// </summary>
private BoundExpression ConvertConcatExprToString(SyntaxNode syntax, BoundExpression expr)
{
// If it's a value type, it'll have been boxed by the +(string, object) or +(object, string)
// operator. Undo that.
if (expr.Kind == BoundKind.Conversion)
{
BoundConversion conv = (BoundConversion)expr;
if (conv.ConversionKind == ConversionKind.Boxing)
{
expr = conv.Operand;
}
}
Debug.Assert(expr.Type is { });
// Is the expression a constant char? If so, we can
// simply make it a literal string instead and avoid any
// allocations for converting the char to a string at run time.
// Similarly if it's a literal null, don't do anything special.
if (expr is { ConstantValue: { } cv })
{
if (cv.SpecialType == SpecialType.System_Char)
{
return _factory.StringLiteral(cv.CharValue.ToString());
}
else if (cv.IsNull)
{
return expr;
}
}
// If it's a string already, just return it
if (expr.Type.IsStringType())
{
return expr;
}
// Evaluate toString at the last possible moment, to avoid spurious diagnostics if it's missing.
// All code paths below here use it.
var objectToStringMethod = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_Object__ToString);
// If it's a struct which has overridden ToString, find that method. Note that we might fail to
// find it, e.g. if object.ToString is missing
MethodSymbol? structToStringMethod = null;
if (expr.Type.IsValueType && !expr.Type.IsTypeParameter())
{
var type = (NamedTypeSymbol)expr.Type;
var typeToStringMembers = type.GetMembers(objectToStringMethod.Name);
foreach (var member in typeToStringMembers)
{
if (member is MethodSymbol toStringMethod &&
toStringMethod.GetLeastOverriddenMethod(type) == (object)objectToStringMethod)
{
structToStringMethod = toStringMethod;
break;
}
}
}
// If it's a special value type (and not a field of a MarshalByRef object), it should have its own ToString method (but we might fail to find
// it if object.ToString is missing). Assume that this won't be removed, and emit a direct call rather
// than a constrained virtual call. This keeps in the spirit of #7079, but expands the range of
// types to all special value types.
if (structToStringMethod != null && (expr.Type.SpecialType != SpecialType.None && !isFieldOfMarshalByRef(expr, _compilation)))
{
return BoundCall.Synthesized(expr.Syntax, expr, structToStringMethod);
}
// - It's a reference type (excluding unconstrained generics): no copy
// - It's a constant: no copy
// - The type definitely doesn't have its own ToString method (i.e. we're definitely calling
// object.ToString on a struct type, not type parameter): no copy (yes this is a versioning issue,
// but that doesn't matter)
// - We're calling the type's own ToString method, and it's effectively readonly (the method or the whole
// type is readonly): no copy
// - Otherwise: copy
// This is to mimic the old behaviour, where value types would be boxed before ToString was called on them,
// but with optimizations for readonly methods.
bool callWithoutCopy = expr.Type.IsReferenceType ||
expr.ConstantValue != null ||
(structToStringMethod == null && !expr.Type.IsTypeParameter()) ||
structToStringMethod?.IsEffectivelyReadOnly == true;
// No need for a conditional access if it's a value type - we know it's not null.
if (expr.Type.IsValueType)
{
if (!callWithoutCopy)
{
expr = new BoundPassByCopy(expr.Syntax, expr, expr.Type);
}
return BoundCall.Synthesized(expr.Syntax, expr, objectToStringMethod);
}
if (callWithoutCopy)
{
return makeConditionalAccess(expr);
}
else
{
// If we do conditional access on a copy, we need a proper BoundLocal rather than a
// BoundPassByCopy (as it's accessed multiple times). If we don't do this, and the
// receiver is an unconstrained generic parameter, BoundLoweredConditionalAccess has
// to generate a lot of code to ensure it only accesses the copy once (which is pointless).
var temp = _factory.StoreToTemp(expr, out var store);
return _factory.Sequence(
ImmutableArray.Create(temp.LocalSymbol),
ImmutableArray.Create<BoundExpression>(store),
makeConditionalAccess(temp));
}
BoundExpression makeConditionalAccess(BoundExpression receiver)
{
int currentConditionalAccessID = ++_currentConditionalAccessID;
return new BoundLoweredConditionalAccess(
syntax,
receiver,
hasValueMethodOpt: null,
whenNotNull: BoundCall.Synthesized(
syntax,
new BoundConditionalReceiver(syntax, currentConditionalAccessID, expr.Type),
objectToStringMethod),
whenNullOpt: null,
id: currentConditionalAccessID,
type: _compilation.GetSpecialType(SpecialType.System_String));
}
static bool isFieldOfMarshalByRef(BoundExpression expr, CSharpCompilation compilation)
{
if (expr is BoundFieldAccess fieldAccess)
{
return DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, compilation);
}
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// The strategy of this rewrite is to do rewrite "locally".
/// We analyze arguments of the concat in a shallow fashion assuming that
/// lowering and optimizations (including this one) is already done for the arguments.
/// Based on the arguments we select the most appropriate pattern for the current node.
///
/// NOTE: it is not guaranteed that the node that we chose will be the most optimal since we have only
/// local information - i.e. we look at the arguments, but we do not know about siblings.
/// When we move to the parent, the node may be rewritten by this or some another optimization.
///
/// Example:
/// result = ( "abc" + "def" + null ?? expr1 + "moo" + "baz" ) + expr2
///
/// Will rewrite into:
/// result = Concat("abcdef", expr2)
///
/// However there will be transient nodes like Concat(expr1 + "moo") that will not be present in the
/// resulting tree.
///
/// </summary>
private BoundExpression RewriteStringConcatenation(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type)
{
Debug.Assert(
operatorKind == BinaryOperatorKind.StringConcatenation ||
operatorKind == BinaryOperatorKind.StringAndObjectConcatenation ||
operatorKind == BinaryOperatorKind.ObjectAndStringConcatenation);
if (_inExpressionLambda)
{
return RewriteStringConcatInExpressionLambda(syntax, operatorKind, loweredLeft, loweredRight, type);
}
// Convert both sides to a string (calling ToString if necessary)
loweredLeft = ConvertConcatExprToString(syntax, loweredLeft);
loweredRight = ConvertConcatExprToString(syntax, loweredRight);
Debug.Assert(loweredLeft.Type is { } && (loweredLeft.Type.IsStringType() || loweredLeft.Type.IsErrorType()) || loweredLeft.ConstantValue?.IsNull == true);
Debug.Assert(loweredRight.Type is { } && (loweredRight.Type.IsStringType() || loweredRight.Type.IsErrorType()) || loweredRight.ConstantValue?.IsNull == true);
// try fold two args without flattening.
var folded = TryFoldTwoConcatOperands(syntax, loweredLeft, loweredRight);
if (folded != null)
{
return folded;
}
// flatten and merge - ( expr1 + "A" ) + ("B" + expr2) ===> (expr1 + "AB" + expr2)
ArrayBuilder<BoundExpression> leftFlattened = ArrayBuilder<BoundExpression>.GetInstance();
ArrayBuilder<BoundExpression> rightFlattened = ArrayBuilder<BoundExpression>.GetInstance();
FlattenConcatArg(loweredLeft, leftFlattened);
FlattenConcatArg(loweredRight, rightFlattened);
if (leftFlattened.Any() && rightFlattened.Any())
{
folded = TryFoldTwoConcatOperands(syntax, leftFlattened.Last(), rightFlattened.First());
if (folded != null)
{
rightFlattened[0] = folded;
leftFlattened.RemoveLast();
}
}
leftFlattened.AddRange(rightFlattened);
rightFlattened.Free();
BoundExpression result;
switch (leftFlattened.Count)
{
case 0:
result = _factory.StringLiteral(string.Empty);
break;
case 1:
// All code paths which reach here (through TryFoldTwoConcatOperands) have already called
// RewriteStringConcatenationOneExpr if necessary
result = leftFlattened[0];
break;
case 2:
var left = leftFlattened[0];
var right = leftFlattened[1];
result = RewriteStringConcatenationTwoExprs(syntax, left, right);
break;
case 3:
{
var first = leftFlattened[0];
var second = leftFlattened[1];
var third = leftFlattened[2];
result = RewriteStringConcatenationThreeExprs(syntax, first, second, third);
}
break;
case 4:
{
var first = leftFlattened[0];
var second = leftFlattened[1];
var third = leftFlattened[2];
var fourth = leftFlattened[3];
result = RewriteStringConcatenationFourExprs(syntax, first, second, third, fourth);
}
break;
default:
result = RewriteStringConcatenationManyExprs(syntax, leftFlattened.ToImmutable());
break;
}
leftFlattened.Free();
return result;
}
/// <summary>
/// digs into known concat operators and unwraps their arguments
/// otherwise returns the expression as-is
///
/// Generally we only need to recognize same node patterns that we create as a result of concatenation rewrite.
/// </summary>
private void FlattenConcatArg(BoundExpression lowered, ArrayBuilder<BoundExpression> flattened)
{
if (TryExtractStringConcatArgs(lowered, out var arguments))
{
flattened.AddRange(arguments);
}
else
{
// fallback - if nothing above worked, leave arg as-is
flattened.Add(lowered);
}
}
/// <summary>
/// Determines whether an expression is a known string concat operator (with or without a subsequent ?? ""), and extracts
/// its args if so.
/// </summary>
/// <returns>True if this is a call to a known string concat operator, false otherwise</returns>
private bool TryExtractStringConcatArgs(BoundExpression lowered, out ImmutableArray<BoundExpression> arguments)
{
switch (lowered.Kind)
{
case BoundKind.Call:
var boundCall = (BoundCall)lowered;
var method = boundCall.Method;
if (method.IsStatic && method.ContainingType.SpecialType == SpecialType.System_String)
{
if ((object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString) ||
(object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringString) ||
(object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringStringStringString))
{
arguments = boundCall.Arguments;
return true;
}
if ((object)method == (object)_compilation.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringArray))
{
var args = boundCall.Arguments[0] as BoundArrayCreation;
if (args != null)
{
var initializer = args.InitializerOpt;
if (initializer != null)
{
arguments = initializer.Initializers;
return true;
}
}
}
}
break;
case BoundKind.NullCoalescingOperator:
var boundCoalesce = (BoundNullCoalescingOperator)lowered;
if (boundCoalesce.LeftConversion.IsIdentity)
{
// The RHS may be a constant value with an identity conversion to string even
// if it is not a string: in particular, the null literal behaves this way.
// To be safe, check that the constant value is actually a string before
// attempting to access its value as a string.
var rightConstant = boundCoalesce.RightOperand.ConstantValue;
if (rightConstant != null && rightConstant.IsString && rightConstant.StringValue.Length == 0)
{
arguments = ImmutableArray.Create(boundCoalesce.LeftOperand);
return true;
}
}
break;
}
arguments = default;
return false;
}
/// <summary>
/// folds two concat operands into one expression if possible
/// otherwise returns null
/// </summary>
private BoundExpression? TryFoldTwoConcatOperands(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight)
{
// both left and right are constants
var leftConst = loweredLeft.ConstantValue;
var rightConst = loweredRight.ConstantValue;
if (leftConst != null && rightConst != null)
{
// const concat may fail to fold if strings are huge.
// This would be unusual.
ConstantValue? concatenated = TryFoldTwoConcatConsts(leftConst, rightConst);
if (concatenated != null)
{
return _factory.StringLiteral(concatenated);
}
}
// one or another is null.
if (IsNullOrEmptyStringConstant(loweredLeft))
{
if (IsNullOrEmptyStringConstant(loweredRight))
{
return _factory.Literal(string.Empty);
}
return RewriteStringConcatenationOneExpr(syntax, loweredRight);
}
else if (IsNullOrEmptyStringConstant(loweredRight))
{
return RewriteStringConcatenationOneExpr(syntax, loweredLeft);
}
return null;
}
private static bool IsNullOrEmptyStringConstant(BoundExpression operand)
{
return (operand.ConstantValue != null && string.IsNullOrEmpty(operand.ConstantValue.StringValue)) ||
operand.IsDefaultValue();
}
/// <summary>
/// folds two concat constants into one if possible
/// otherwise returns null.
/// It is generally always possible to concat constants, unless resulting string would be too large.
/// </summary>
private static ConstantValue? TryFoldTwoConcatConsts(ConstantValue leftConst, ConstantValue rightConst)
{
var leftVal = leftConst.StringValue;
var rightVal = rightConst.StringValue;
if (!leftConst.IsDefaultValue && !rightConst.IsDefaultValue)
{
Debug.Assert(leftVal is { } && rightVal is { });
if (leftVal.Length + rightVal.Length < 0)
{
return null;
}
}
// TODO: if transient string allocations are an issue, consider introducing constants that contain builders.
// it may be not so easy to even get here though, since typical
// "A" + "B" + "C" + ... cases should be folded in the binder as spec requires so.
// we would be mostly picking here edge cases like "A" + (object)null + "B" + (object)null + ...
return ConstantValue.Create(leftVal + rightVal);
}
/// <summary>
/// Strangely enough there is such a thing as unary concatenation and it must be rewritten.
/// </summary>
private BoundExpression RewriteStringConcatenationOneExpr(SyntaxNode syntax, BoundExpression loweredOperand)
{
// If it's a call to 'string.Concat' (or is something which ends in '?? ""', which this method also extracts),
// we know the result cannot be null. Otherwise return loweredOperand ?? ""
if (TryExtractStringConcatArgs(loweredOperand, out _))
{
return loweredOperand;
}
else
{
return _factory.Coalesce(loweredOperand, _factory.Literal(""));
}
}
private BoundExpression RewriteStringConcatenationTwoExprs(SyntaxNode syntax, BoundExpression loweredLeft, BoundExpression loweredRight)
{
Debug.Assert(loweredLeft.HasAnyErrors || loweredLeft.Type is { } && loweredLeft.Type.IsStringType());
Debug.Assert(loweredRight.HasAnyErrors || loweredRight.Type is { } && loweredRight.Type.IsStringType());
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringString);
Debug.Assert((object)method != null);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, loweredLeft, loweredRight);
}
private BoundExpression RewriteStringConcatenationThreeExprs(SyntaxNode syntax, BoundExpression loweredFirst, BoundExpression loweredSecond, BoundExpression loweredThird)
{
Debug.Assert(loweredFirst.HasAnyErrors || loweredFirst.Type is { } && loweredFirst.Type.IsStringType());
Debug.Assert(loweredSecond.HasAnyErrors || loweredSecond.Type is { } && loweredSecond.Type.IsStringType());
Debug.Assert(loweredThird.HasAnyErrors || loweredThird.Type is { } && loweredThird.Type.IsStringType());
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringStringString);
Debug.Assert((object)method != null);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, ImmutableArray.Create(loweredFirst, loweredSecond, loweredThird));
}
private BoundExpression RewriteStringConcatenationFourExprs(SyntaxNode syntax, BoundExpression loweredFirst, BoundExpression loweredSecond, BoundExpression loweredThird, BoundExpression loweredFourth)
{
Debug.Assert(loweredFirst.HasAnyErrors || loweredFirst.Type is { } && loweredFirst.Type.IsStringType());
Debug.Assert(loweredSecond.HasAnyErrors || loweredSecond.Type is { } && loweredSecond.Type.IsStringType());
Debug.Assert(loweredThird.HasAnyErrors || loweredThird.Type is { } && loweredThird.Type.IsStringType());
Debug.Assert(loweredFourth.HasAnyErrors || loweredFourth.Type is { } && loweredFourth.Type.IsStringType());
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringStringStringString);
Debug.Assert((object)method != null);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, ImmutableArray.Create(loweredFirst, loweredSecond, loweredThird, loweredFourth));
}
private BoundExpression RewriteStringConcatenationManyExprs(SyntaxNode syntax, ImmutableArray<BoundExpression> loweredArgs)
{
Debug.Assert(loweredArgs.Length > 4);
Debug.Assert(loweredArgs.All(a => a.HasErrors || a.Type is { } && a.Type.IsStringType()));
var method = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_String__ConcatStringArray);
Debug.Assert((object)method != null);
var array = _factory.ArrayOrEmpty(_factory.SpecialType(SpecialType.System_String), loweredArgs);
return BoundCall.Synthesized(syntax, receiverOpt: null, method, array);
}
/// <summary>
/// Most of the above optimizations are not applicable in expression trees as the operator
/// must stay a binary operator. We cannot do much beyond constant folding which is done in binder.
/// </summary>
private BoundExpression RewriteStringConcatInExpressionLambda(SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, TypeSymbol type)
{
SpecialMember member = (operatorKind == BinaryOperatorKind.StringConcatenation) ?
SpecialMember.System_String__ConcatStringString :
SpecialMember.System_String__ConcatObjectObject;
var method = UnsafeGetSpecialTypeMethod(syntax, member);
Debug.Assert((object)method != null);
return new BoundBinaryOperator(syntax, operatorKind, constantValueOpt: null, method, constrainedToTypeOpt: null, default(LookupResultKind), loweredLeft, loweredRight, type);
}
/// <summary>
/// Returns an expression which converts the given expression into a string (or null).
/// If necessary, this invokes .ToString() on the expression, to avoid boxing value types.
/// </summary>
private BoundExpression ConvertConcatExprToString(SyntaxNode syntax, BoundExpression expr)
{
// If it's a value type, it'll have been boxed by the +(string, object) or +(object, string)
// operator. Undo that.
if (expr.Kind == BoundKind.Conversion)
{
BoundConversion conv = (BoundConversion)expr;
if (conv.ConversionKind == ConversionKind.Boxing)
{
expr = conv.Operand;
}
}
Debug.Assert(expr.Type is { });
// Is the expression a constant char? If so, we can
// simply make it a literal string instead and avoid any
// allocations for converting the char to a string at run time.
// Similarly if it's a literal null, don't do anything special.
if (expr is { ConstantValue: { } cv })
{
if (cv.SpecialType == SpecialType.System_Char)
{
return _factory.StringLiteral(cv.CharValue.ToString());
}
else if (cv.IsNull)
{
return expr;
}
}
// If it's a string already, just return it
if (expr.Type.IsStringType())
{
return expr;
}
// Evaluate toString at the last possible moment, to avoid spurious diagnostics if it's missing.
// All code paths below here use it.
var objectToStringMethod = UnsafeGetSpecialTypeMethod(syntax, SpecialMember.System_Object__ToString);
// If it's a struct which has overridden ToString, find that method. Note that we might fail to
// find it, e.g. if object.ToString is missing
MethodSymbol? structToStringMethod = null;
if (expr.Type.IsValueType && !expr.Type.IsTypeParameter())
{
var type = (NamedTypeSymbol)expr.Type;
var typeToStringMembers = type.GetMembers(objectToStringMethod.Name);
foreach (var member in typeToStringMembers)
{
if (member is MethodSymbol toStringMethod &&
toStringMethod.GetLeastOverriddenMethod(type) == (object)objectToStringMethod)
{
structToStringMethod = toStringMethod;
break;
}
}
}
// If it's a special value type (and not a field of a MarshalByRef object), it should have its own ToString method (but we might fail to find
// it if object.ToString is missing). Assume that this won't be removed, and emit a direct call rather
// than a constrained virtual call. This keeps in the spirit of #7079, but expands the range of
// types to all special value types.
if (structToStringMethod != null && (expr.Type.SpecialType != SpecialType.None && !isFieldOfMarshalByRef(expr, _compilation)))
{
return BoundCall.Synthesized(expr.Syntax, expr, structToStringMethod);
}
// - It's a reference type (excluding unconstrained generics): no copy
// - It's a constant: no copy
// - The type definitely doesn't have its own ToString method (i.e. we're definitely calling
// object.ToString on a struct type, not type parameter): no copy (yes this is a versioning issue,
// but that doesn't matter)
// - We're calling the type's own ToString method, and it's effectively readonly (the method or the whole
// type is readonly): no copy
// - Otherwise: copy
// This is to mimic the old behaviour, where value types would be boxed before ToString was called on them,
// but with optimizations for readonly methods.
bool callWithoutCopy = expr.Type.IsReferenceType ||
expr.ConstantValue != null ||
(structToStringMethod == null && !expr.Type.IsTypeParameter()) ||
structToStringMethod?.IsEffectivelyReadOnly == true;
// No need for a conditional access if it's a value type - we know it's not null.
if (expr.Type.IsValueType)
{
if (!callWithoutCopy)
{
expr = new BoundPassByCopy(expr.Syntax, expr, expr.Type);
}
return BoundCall.Synthesized(expr.Syntax, expr, objectToStringMethod);
}
if (callWithoutCopy)
{
return makeConditionalAccess(expr);
}
else
{
// If we do conditional access on a copy, we need a proper BoundLocal rather than a
// BoundPassByCopy (as it's accessed multiple times). If we don't do this, and the
// receiver is an unconstrained generic parameter, BoundLoweredConditionalAccess has
// to generate a lot of code to ensure it only accesses the copy once (which is pointless).
var temp = _factory.StoreToTemp(expr, out var store);
return _factory.Sequence(
ImmutableArray.Create(temp.LocalSymbol),
ImmutableArray.Create<BoundExpression>(store),
makeConditionalAccess(temp));
}
BoundExpression makeConditionalAccess(BoundExpression receiver)
{
int currentConditionalAccessID = ++_currentConditionalAccessID;
return new BoundLoweredConditionalAccess(
syntax,
receiver,
hasValueMethodOpt: null,
whenNotNull: BoundCall.Synthesized(
syntax,
new BoundConditionalReceiver(syntax, currentConditionalAccessID, expr.Type),
objectToStringMethod),
whenNullOpt: null,
id: currentConditionalAccessID,
type: _compilation.GetSpecialType(SpecialType.System_String));
}
static bool isFieldOfMarshalByRef(BoundExpression expr, CSharpCompilation compilation)
{
if (expr is BoundFieldAccess fieldAccess)
{
return DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, compilation);
}
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/KeywordHighlighting/AbstractCSharpKeywordHighlighterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public abstract class AbstractCSharpKeywordHighlighterTests
: AbstractKeywordHighlighterTests
{
protected override TestWorkspace CreateWorkspaceFromFile(string code, ParseOptions options)
=> TestWorkspace.CreateCSharp(code, options, composition: Composition);
protected override IEnumerable<ParseOptions> GetOptions()
{
yield return Options.Regular;
yield return Options.Script;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.UnitTests.KeywordHighlighting;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public abstract class AbstractCSharpKeywordHighlighterTests
: AbstractKeywordHighlighterTests
{
protected override TestWorkspace CreateWorkspaceFromFile(string code, ParseOptions options)
=> TestWorkspace.CreateCSharp(code, options, composition: Composition);
protected override IEnumerable<ParseOptions> GetOptions()
{
yield return Options.Regular;
yield return Options.Script;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyCompilationsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "No change to symbol"
[Fact]
public void C2CTypeSymbolUnchanged01()
{
var src1 = @"using System;
public delegate void DGoo(int p1, string p2);
namespace N1.N2
{
public interface IGoo { }
namespace N3
{
public class CGoo
{
public struct SGoo
{
public enum EGoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DGoo(int p1, string p2);
namespace N1.N2
{
public interface IGoo
{
// Add member
N3.CGoo GetClass();
}
namespace N3
{
public class CGoo
{
public struct SGoo
{
// Update member
public enum EGoo { Zero, One, Two }
}
// Add member
public void M(int n) { Console.WriteLine(n); }
}
}
}
";
var comp1 = CreateCompilation(src1, assemblyName: "Test");
var comp2 = CreateCompilation(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")]
public void C2CErrorSymbolUnchanged01()
{
var src1 = @"public void Method() { }";
var src2 = @"
public void Method()
{
System.Console.WriteLine(12345);
}
";
var comp1 = CreateCompilation(src1, assemblyName: "C2CErrorSymbolUnchanged01");
var comp2 = CreateCompilation(src2, assemblyName: "C2CErrorSymbolUnchanged01");
var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
Assert.NotNull(symbol01);
Assert.NotNull(symbol02);
Assert.NotEqual(SymbolKind.ErrorType, symbol01.Kind);
Assert.NotEqual(SymbolKind.ErrorType, symbol02.Kind);
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
[WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")]
public void PartialDefinitionAndImplementationResolveCorrectly()
{
var src = @"using System;
namespace NS
{
public partial class C1
{
partial void M() { }
partial void M();
}
}
";
var comp = (Compilation)CreateCompilation(src, assemblyName: "Test");
var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var definition = type.GetMembers("M").First() as IMethodSymbol;
var implementation = definition.PartialImplementationPart;
// Assert that both the definition and implementation resolve back to themselves
Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None));
Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None));
}
[Fact]
public void ExtendedPartialDefinitionAndImplementationResolveCorrectly()
{
var src = @"using System;
namespace NS
{
public partial class C1
{
public partial void M() { }
public partial void M();
}
}
";
var comp = (Compilation)CreateCompilation(src, assemblyName: "Test");
var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var definition = type.GetMembers("M").First() as IMethodSymbol;
var implementation = definition.PartialImplementationPart;
// Assert that both the definition and implementation resolve back to themselves
Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None));
Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None));
}
[Fact]
[WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")]
public void ExplicitIndexerImplementationResolvesCorrectly()
{
var src = @"
interface I
{
object this[int index] { get; }
}
interface I<T>
{
T this[int index] { get; }
}
class C<T> : I<T>, I
{
object I.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
T I<T>.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
}
";
var compilation = (Compilation)CreateCompilation(src, assemblyName: "Test");
var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as INamedTypeSymbol;
var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol;
var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol;
AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false);
Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None));
Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None));
}
[Fact]
public void RecursiveReferenceToConstructedGeneric()
{
var src1 =
@"using System.Collections.Generic;
class C
{
public void M<Z>(List<Z> list)
{
var v = list.Add(default(Z));
}
}";
var comp1 = CreateCompilation(src1);
var comp2 = CreateCompilation(src1);
var symbols1 = GetSourceSymbols(comp1, includeLocal: true).ToList();
var symbols2 = GetSourceSymbols(comp1, includeLocal: true).ToList();
// First, make sure that all the symbols in this file resolve properly
// to themselves.
ResolveAndVerifySymbolList(symbols1, symbols2, comp1);
// Now do this for the members of types we see. We want this
// so we hit things like the members of the constructed type
// List<Z>
var members1 = symbols1.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList();
var members2 = symbols2.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList();
ResolveAndVerifySymbolList(members1, members2, comp1);
}
#endregion
#region "Change to symbol"
[Fact]
public void C2CTypeSymbolChanged01()
{
var src1 = @"using System;
public delegate void DGoo(int p1);
namespace N1.N2
{
public interface IBase { }
public interface IGoo { }
namespace N3
{
public class CGoo
{
public struct SGoo
{
public enum EGoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DGoo(int p1, string p2); // add 1 more parameter
namespace N1.N2
{
public interface IBase { }
public interface IGoo : IBase // add base interface
{
}
namespace N3
{
public class CGoo : IGoo // impl interface
{
private struct SGoo // change modifier
{
internal enum EGoo : long { Zero, One } // change base class, and modifier
}
}
}
}
";
var comp1 = CreateCompilation(src1, assemblyName: "Test");
var comp2 = CreateCompilation(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
public void C2CTypeSymbolChanged02()
{
var src1 = @"using System;
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var src2 = @"
namespace NS
{
internal class C1 // add new C1
{
public string P { get; set; }
}
public class C2 // rename C1 to C2
{
public void M() {}
}
}
";
var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test");
var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var typeSym02 = namespace2.GetTypeMembers("C2").Single() as INamedTypeSymbol;
// new C1 resolve to old C1
ResolveAndVerifySymbol(typeSym01, typeSym00, comp1);
// old C1 (new C2) NOT resolve to old C1
var symkey = SymbolKey.Create(typeSym02, CancellationToken.None);
var syminfo = symkey.Resolve(comp1);
Assert.Null(syminfo.Symbol);
}
[Fact]
public void C2CMemberSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
private byte field = 123;
internal string P { get; set; }
public void M(ref int n) { }
event Action<string> myEvent;
}
";
var src2 = @"using System;
public class Test
{
internal protected byte field = 255; // change modifier and init-value
internal string P { get { return null; } } // remove 'set'
public int M(ref int n) { return 0; } // change ret type
event Action<string> myEvent // add add/remove
{
add { }
remove { }
}
}
";
var comp1 = CreateCompilation(src1, assemblyName: "Test");
var comp2 = CreateCompilation(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void C2CIndexerSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
public string this[string p1] { set { } }
protected long this[long p1] { set { } }
}
";
var src2 = @"using System;
public class Test
{
internal string this[string p1] { set { } } // change modifier
protected long this[long p1] { get { return 0; } set { } } // add 'get'
}
";
var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test");
var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test");
var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol;
var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer);
var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol;
var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer);
ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None);
}
[Fact]
public void C2CAssemblyChanged01()
{
var src = @"
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1");
var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
// new C1 resolves to old C1 if we ignore assembly and module ids
ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds);
// new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids
Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None));
}
[WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")]
public void C2CAssemblyChanged02()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// same identity
var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly");
var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly");
ISymbol sym1 = comp1.Assembly;
ISymbol sym2 = comp2.Assembly;
// Not ignoreAssemblyAndModules
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
sym1 = comp1.Assembly.Modules.First();
sym2 = comp2.Assembly.Modules.First();
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")]
public void C2CAssemblyChanged03()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// -------------------------------------------------------
// different name
var compilation1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1");
var compilation2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2");
ISymbol assembly1 = compilation1.Assembly;
ISymbol assembly2 = compilation2.Assembly;
// different
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None));
// ignore means ALL assembly/module symbols have same ID
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true);
// But can NOT be resolved
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
var module1 = compilation1.Assembly.Modules.First();
var module2 = compilation2.Assembly.Modules.First();
// different
AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None));
AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")]
public void C2CAssemblyChanged04()
{
var src = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
var src2 = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
// different versions
var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly");
var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Assembly");
ISymbol sym1 = comp1.Assembly;
ISymbol sym2 = comp2.Assembly;
// comment is changed to compare Name ONLY
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true);
var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None);
Assert.Equal(sym1, resolved);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "No change to symbol"
[Fact]
public void C2CTypeSymbolUnchanged01()
{
var src1 = @"using System;
public delegate void DGoo(int p1, string p2);
namespace N1.N2
{
public interface IGoo { }
namespace N3
{
public class CGoo
{
public struct SGoo
{
public enum EGoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DGoo(int p1, string p2);
namespace N1.N2
{
public interface IGoo
{
// Add member
N3.CGoo GetClass();
}
namespace N3
{
public class CGoo
{
public struct SGoo
{
// Update member
public enum EGoo { Zero, One, Two }
}
// Add member
public void M(int n) { Console.WriteLine(n); }
}
}
}
";
var comp1 = CreateCompilation(src1, assemblyName: "Test");
var comp2 = CreateCompilation(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")]
public void C2CErrorSymbolUnchanged01()
{
var src1 = @"public void Method() { }";
var src2 = @"
public void Method()
{
System.Console.WriteLine(12345);
}
";
var comp1 = CreateCompilation(src1, assemblyName: "C2CErrorSymbolUnchanged01");
var comp2 = CreateCompilation(src2, assemblyName: "C2CErrorSymbolUnchanged01");
var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
Assert.NotNull(symbol01);
Assert.NotNull(symbol02);
Assert.NotEqual(SymbolKind.ErrorType, symbol01.Kind);
Assert.NotEqual(SymbolKind.ErrorType, symbol02.Kind);
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
[WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")]
public void PartialDefinitionAndImplementationResolveCorrectly()
{
var src = @"using System;
namespace NS
{
public partial class C1
{
partial void M() { }
partial void M();
}
}
";
var comp = (Compilation)CreateCompilation(src, assemblyName: "Test");
var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var definition = type.GetMembers("M").First() as IMethodSymbol;
var implementation = definition.PartialImplementationPart;
// Assert that both the definition and implementation resolve back to themselves
Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None));
Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None));
}
[Fact]
public void ExtendedPartialDefinitionAndImplementationResolveCorrectly()
{
var src = @"using System;
namespace NS
{
public partial class C1
{
public partial void M() { }
public partial void M();
}
}
";
var comp = (Compilation)CreateCompilation(src, assemblyName: "Test");
var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var definition = type.GetMembers("M").First() as IMethodSymbol;
var implementation = definition.PartialImplementationPart;
// Assert that both the definition and implementation resolve back to themselves
Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None));
Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None));
}
[Fact]
[WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")]
public void ExplicitIndexerImplementationResolvesCorrectly()
{
var src = @"
interface I
{
object this[int index] { get; }
}
interface I<T>
{
T this[int index] { get; }
}
class C<T> : I<T>, I
{
object I.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
T I<T>.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
}
";
var compilation = (Compilation)CreateCompilation(src, assemblyName: "Test");
var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as INamedTypeSymbol;
var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol;
var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol;
AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false);
Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None));
Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None));
}
[Fact]
public void RecursiveReferenceToConstructedGeneric()
{
var src1 =
@"using System.Collections.Generic;
class C
{
public void M<Z>(List<Z> list)
{
var v = list.Add(default(Z));
}
}";
var comp1 = CreateCompilation(src1);
var comp2 = CreateCompilation(src1);
var symbols1 = GetSourceSymbols(comp1, includeLocal: true).ToList();
var symbols2 = GetSourceSymbols(comp1, includeLocal: true).ToList();
// First, make sure that all the symbols in this file resolve properly
// to themselves.
ResolveAndVerifySymbolList(symbols1, symbols2, comp1);
// Now do this for the members of types we see. We want this
// so we hit things like the members of the constructed type
// List<Z>
var members1 = symbols1.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList();
var members2 = symbols2.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList();
ResolveAndVerifySymbolList(members1, members2, comp1);
}
#endregion
#region "Change to symbol"
[Fact]
public void C2CTypeSymbolChanged01()
{
var src1 = @"using System;
public delegate void DGoo(int p1);
namespace N1.N2
{
public interface IBase { }
public interface IGoo { }
namespace N3
{
public class CGoo
{
public struct SGoo
{
public enum EGoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DGoo(int p1, string p2); // add 1 more parameter
namespace N1.N2
{
public interface IBase { }
public interface IGoo : IBase // add base interface
{
}
namespace N3
{
public class CGoo : IGoo // impl interface
{
private struct SGoo // change modifier
{
internal enum EGoo : long { Zero, One } // change base class, and modifier
}
}
}
}
";
var comp1 = CreateCompilation(src1, assemblyName: "Test");
var comp2 = CreateCompilation(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
public void C2CTypeSymbolChanged02()
{
var src1 = @"using System;
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var src2 = @"
namespace NS
{
internal class C1 // add new C1
{
public string P { get; set; }
}
public class C2 // rename C1 to C2
{
public void M() {}
}
}
";
var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test");
var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var typeSym02 = namespace2.GetTypeMembers("C2").Single() as INamedTypeSymbol;
// new C1 resolve to old C1
ResolveAndVerifySymbol(typeSym01, typeSym00, comp1);
// old C1 (new C2) NOT resolve to old C1
var symkey = SymbolKey.Create(typeSym02, CancellationToken.None);
var syminfo = symkey.Resolve(comp1);
Assert.Null(syminfo.Symbol);
}
[Fact]
public void C2CMemberSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
private byte field = 123;
internal string P { get; set; }
public void M(ref int n) { }
event Action<string> myEvent;
}
";
var src2 = @"using System;
public class Test
{
internal protected byte field = 255; // change modifier and init-value
internal string P { get { return null; } } // remove 'set'
public int M(ref int n) { return 0; } // change ret type
event Action<string> myEvent // add add/remove
{
add { }
remove { }
}
}
";
var comp1 = CreateCompilation(src1, assemblyName: "Test");
var comp2 = CreateCompilation(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void C2CIndexerSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
public string this[string p1] { set { } }
protected long this[long p1] { set { } }
}
";
var src2 = @"using System;
public class Test
{
internal string this[string p1] { set { } } // change modifier
protected long this[long p1] { get { return 0; } set { } } // add 'get'
}
";
var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test");
var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test");
var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol;
var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer);
var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol;
var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer);
ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None);
}
[Fact]
public void C2CAssemblyChanged01()
{
var src = @"
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1");
var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol;
var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol;
// new C1 resolves to old C1 if we ignore assembly and module ids
ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds);
// new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids
Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None));
}
[WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")]
public void C2CAssemblyChanged02()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// same identity
var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly");
var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly");
ISymbol sym1 = comp1.Assembly;
ISymbol sym2 = comp2.Assembly;
// Not ignoreAssemblyAndModules
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
sym1 = comp1.Assembly.Modules.First();
sym2 = comp2.Assembly.Modules.First();
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")]
public void C2CAssemblyChanged03()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// -------------------------------------------------------
// different name
var compilation1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1");
var compilation2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2");
ISymbol assembly1 = compilation1.Assembly;
ISymbol assembly2 = compilation2.Assembly;
// different
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None));
// ignore means ALL assembly/module symbols have same ID
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true);
// But can NOT be resolved
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
var module1 = compilation1.Assembly.Modules.First();
var module2 = compilation2.Assembly.Modules.First();
// different
AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None));
AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")]
public void C2CAssemblyChanged04()
{
var src = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
var src2 = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
// different versions
var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly");
var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Assembly");
ISymbol sym1 = comp1.Assembly;
ISymbol sym2 = comp2.Assembly;
// comment is changed to compare Name ONLY
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true);
var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None);
Assert.Equal(sym1, resolved);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Binder/Semantics/AccessCheck.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Contains the code for determining C# accessibility rules.
/// </summary>
internal static class AccessCheck
{
/// <summary>
/// Checks if 'symbol' is accessible from within assembly 'within'.
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
AssemblySymbol within,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
bool failedThroughTypeCheck;
return IsSymbolAccessibleCore(symbol, within, null, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo);
}
/// <summary>
/// Checks if 'symbol' is accessible from within type 'within', with
/// an optional qualifier of type "throughTypeOpt".
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
NamedTypeSymbol within,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
TypeSymbol throughTypeOpt = null)
{
bool failedThroughTypeCheck;
return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo);
}
/// <summary>
/// Checks if 'symbol' is accessible from within type 'within', with
/// a qualifier of type "throughTypeOpt". Sets "failedThroughTypeCheck" to true
/// if it failed the "through type" check.
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
NamedTypeSymbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo, basesBeingResolved);
}
/// <summary>
/// Returns true if the symbol is effectively public or internal based on
/// the declared accessibility of the symbol and any containing symbols.
/// </summary>
internal static bool IsEffectivelyPublicOrInternal(Symbol symbol, out bool isInternal)
{
Debug.Assert(symbol is object);
switch (symbol.Kind)
{
case SymbolKind.NamedType:
case SymbolKind.Event:
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.Property:
break;
case SymbolKind.TypeParameter:
symbol = symbol.ContainingSymbol;
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
isInternal = false;
do
{
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
case Accessibility.Protected:
case Accessibility.ProtectedOrInternal:
break;
case Accessibility.Internal:
case Accessibility.ProtectedAndInternal:
isInternal = true;
break;
case Accessibility.Private:
return false;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility);
}
symbol = symbol.ContainingType;
}
while (symbol is object);
return true;
}
/// <summary>
/// Checks if 'symbol' is accessible from within 'within', which must be a NamedTypeSymbol
/// or an AssemblySymbol.
/// </summary>
/// <remarks>
/// Note that NamedTypeSymbol, if available, is the type that is associated with the binder
/// that found the 'symbol', not the inner-most type that contains the access to the
/// 'symbol'.
/// <para>
/// If 'symbol' is accessed off of an expression then 'throughTypeOpt' is the type of that
/// expression. This is needed to properly do protected access checks. Sets
/// "failedThroughTypeCheck" to true if this protected check failed.
/// </para>
/// <para>
/// This function is expected to be called a lot. As such, it avoids memory
/// allocations in the function itself (including not making any iterators). This means
/// that certain helper functions that could otherwise be called are inlined in this method to
/// prevent the overhead of returning collections or enumerators.
/// </para>
/// </remarks>
private static bool IsSymbolAccessibleCore(
Symbol symbol,
Symbol within, // must be assembly or named type symbol
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert((object)symbol != null);
Debug.Assert((object)within != null);
Debug.Assert(within.IsDefinition);
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
failedThroughTypeCheck = false;
switch (symbol.Kind)
{
case SymbolKind.ArrayType:
return IsSymbolAccessibleCore(((ArrayTypeSymbol)symbol).ElementType, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.PointerType:
return IsSymbolAccessibleCore(((PointerTypeSymbol)symbol).PointedAtType, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.NamedType:
return IsNamedTypeAccessible((NamedTypeSymbol)symbol, within, ref useSiteInfo, basesBeingResolved);
case SymbolKind.Alias:
return IsSymbolAccessibleCore(((AliasSymbol)symbol).Target, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.Discard:
return IsSymbolAccessibleCore(((DiscardSymbol)symbol).TypeWithAnnotations.Type, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.FunctionPointerType:
var funcPtr = (FunctionPointerTypeSymbol)symbol;
if (!IsSymbolAccessibleCore(funcPtr.Signature.ReturnType, within, throughTypeOpt: null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved))
{
return false;
}
foreach (var param in funcPtr.Signature.Parameters)
{
if (!IsSymbolAccessibleCore(param.Type, within, throughTypeOpt: null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved))
{
return false;
}
}
return true;
case SymbolKind.ErrorType:
// Always assume that error types are accessible.
return true;
case SymbolKind.TypeParameter:
case SymbolKind.Parameter:
case SymbolKind.Local:
case SymbolKind.Label:
case SymbolKind.Namespace:
case SymbolKind.DynamicType:
case SymbolKind.Assembly:
case SymbolKind.NetModule:
case SymbolKind.RangeVariable:
case SymbolKind.Method when ((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction:
// These types of symbols are always accessible (if visible).
return true;
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
case SymbolKind.Field:
if (!symbol.RequiresInstanceReceiver())
{
// static members aren't accessed "through" an "instance" of any type. So we
// null out the "through" instance here. This ensures that we'll understand
// accessing protected statics properly.
throughTypeOpt = null;
}
return IsMemberAccessible(symbol.ContainingType, symbol.DeclaredAccessibility, within, throughTypeOpt, out failedThroughTypeCheck, compilation, ref useSiteInfo);
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
/// <summary>
/// Is the named type <paramref name="type"/> accessible from within <paramref name="within"/>,
/// which must be a named type or an assembly.
/// </summary>
private static bool IsNamedTypeAccessible(NamedTypeSymbol type, Symbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)type != null);
var compilation = within.DeclaringCompilation;
bool unused;
if (!type.IsDefinition)
{
// All type argument must be accessible.
var typeArgs = type.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
foreach (var typeArg in typeArgs)
{
// type parameters are always accessible, so don't check those (so common it's
// worth optimizing this).
if (typeArg.Type.Kind != SymbolKind.TypeParameter && !IsSymbolAccessibleCore(typeArg.Type, within, null, out unused, compilation, ref useSiteInfo, basesBeingResolved))
{
return false;
}
}
}
var containingType = type.ContainingType;
return (object)containingType == null
? IsNonNestedTypeAccessible(type.ContainingAssembly, type.DeclaredAccessibility, within)
: IsMemberAccessible(containingType, type.DeclaredAccessibility, within, null, out unused, compilation, ref useSiteInfo, basesBeingResolved);
}
/// <summary>
/// Is a top-level type with accessibility "declaredAccessibility" inside assembly "assembly"
/// accessible from "within", which must be a named type of an assembly.
/// </summary>
private static bool IsNonNestedTypeAccessible(
AssemblySymbol assembly,
Accessibility declaredAccessibility,
Symbol within)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)assembly != null);
switch (declaredAccessibility)
{
case Accessibility.NotApplicable:
case Accessibility.Public:
// Public symbols are always accessible from any context
return true;
case Accessibility.Private:
case Accessibility.Protected:
case Accessibility.ProtectedAndInternal:
// Shouldn't happen except in error cases.
return false;
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal:
// within is typically a type
var withinType = within as NamedTypeSymbol;
var withinAssembly = (object)withinType != null ? withinType.ContainingAssembly : (AssemblySymbol)within;
// An internal type is accessible if we're in the same assembly or we have
// friend access to the assembly it was defined in.
return (object)withinAssembly == (object)assembly || withinAssembly.HasInternalAccessTo(assembly);
default:
throw ExceptionUtilities.UnexpectedValue(declaredAccessibility);
}
}
/// <summary>
/// Is a member with declared accessibility "declaredAccessibility" accessible from within
/// "within", which must be a named type or an assembly.
/// </summary>
private static bool IsMemberAccessible(
NamedTypeSymbol containingType, // the symbol's containing type
Accessibility declaredAccessibility,
Symbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)containingType != null);
failedThroughTypeCheck = false;
// easy case - members of containing type are accessible.
if ((object)containingType == (object)within)
{
return true;
}
// A nested symbol is only accessible to us if its container is accessible as well.
if (!IsNamedTypeAccessible(containingType, within, ref useSiteInfo, basesBeingResolved))
{
return false;
}
// public in accessible type is accessible
if (declaredAccessibility == Accessibility.Public)
{
return true;
}
return IsNonPublicMemberAccessible(
containingType,
declaredAccessibility,
within,
throughTypeOpt,
out failedThroughTypeCheck,
compilation,
ref useSiteInfo,
basesBeingResolved);
}
private static bool IsNonPublicMemberAccessible(
NamedTypeSymbol containingType, // the symbol's containing type
Accessibility declaredAccessibility,
Symbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
failedThroughTypeCheck = false;
var originalContainingType = containingType.OriginalDefinition;
var withinType = within as NamedTypeSymbol;
var withinAssembly = (object)withinType != null ? withinType.ContainingAssembly : (AssemblySymbol)within;
switch (declaredAccessibility)
{
case Accessibility.NotApplicable:
return true;
case Accessibility.Private:
// All expressions in the current submission (top-level or nested in a method or
// type) can access previous submission's private top-level members. Previous
// submissions are treated like outer classes for the current submission - the
// inner class can access private members of the outer class.
if (containingType.TypeKind == TypeKind.Submission)
{
return true;
}
// private members never accessible from outside a type.
return (object)withinType != null && IsPrivateSymbolAccessible(withinType, originalContainingType);
case Accessibility.Internal:
// An internal type is accessible if we're in the same assembly or we have
// friend access to the assembly it was defined in.
return withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly);
case Accessibility.ProtectedAndInternal:
if (!withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly))
{
// We require internal access. If we don't have it, then this symbol is
// definitely not accessible to us.
return false;
}
// We had internal access. Also have to make sure we have protected access.
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case Accessibility.ProtectedOrInternal:
if (withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly))
{
// If we have internal access to this symbol, then that's sufficient. no
// need to do the complicated protected case.
return true;
}
// We don't have internal access. But if we have protected access then that's
// sufficient.
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case Accessibility.Protected:
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
default:
throw ExceptionUtilities.UnexpectedValue(declaredAccessibility);
}
}
/// <summary>
/// Is a protected symbol inside "originalContainingType" accessible from within "within",
/// which much be a named type or an assembly.
/// </summary>
private static bool IsProtectedSymbolAccessible(
NamedTypeSymbol withinType,
TypeSymbol throughTypeOpt,
NamedTypeSymbol originalContainingType,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
failedThroughTypeCheck = false;
// It is not an error to define protected member in a sealed Script class, it's just a
// warning. The member behaves like a private one - it is visible in all subsequent
// submissions.
if (originalContainingType.TypeKind == TypeKind.Submission)
{
return true;
}
if ((object)withinType == null)
{
// If we're not within a type, we can't access a protected symbol
return false;
}
// A protected symbol is accessible if we're (optionally nested) inside the type that it
// was defined in.
// It is helpful to think about 'protected' as *increasing* the
// accessibility domain of a private member, rather than *decreasing* that of a public
// member. Members are naturally private; the protected, internal and public access
// modifiers all increase the accessibility domain. Since private members are accessible
// to nested types, so are protected members.
// We do this check up front as it is very fast and easy to do.
if (IsNestedWithinOriginalContainingType(withinType, originalContainingType))
{
return true;
}
// Protected is really confusing. Check out 3.5.3 of the language spec "protected access
// for instance members" to see how it works. I actually got the code for this from
// LangCompiler::CheckAccessCore
{
var current = withinType.OriginalDefinition;
var originalThroughTypeOpt = (object)throughTypeOpt == null ? null : throughTypeOpt.OriginalDefinition as TypeSymbol;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (current.InheritsFromOrImplementsIgnoringConstruction(originalContainingType, compilation, ref useSiteInfo, basesBeingResolved))
{
// NOTE(cyrusn): We're continually walking up the 'throughType's inheritance
// chain. We could compute it up front and cache it in a set. However, we
// don't want to allocate memory in this function. Also, in practice
// inheritance chains should be very short. As such, it might actually be
// slower to create and check inside the set versus just walking the
// inheritance chain.
if ((object)originalThroughTypeOpt == null ||
originalThroughTypeOpt.InheritsFromOrImplementsIgnoringConstruction(current, compilation, ref useSiteInfo))
{
return true;
}
else
{
failedThroughTypeCheck = true;
}
}
// NOTE(cyrusn): The container of an original type is always original.
current = current.ContainingType;
}
}
return false;
}
private static bool IsPrivateSymbolAccessible(
Symbol within,
NamedTypeSymbol originalContainingType)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
var withinType = within as NamedTypeSymbol;
if ((object)withinType == null)
{
// If we're not within a type, we can't access a private symbol
return false;
}
// A private symbol is accessible if we're (optionally nested) inside the type that it
// was defined in.
return IsNestedWithinOriginalContainingType(withinType, originalContainingType);
}
/// <summary>
/// Is the type "withinType" nested within the original type "originalContainingType".
/// </summary>
private static bool IsNestedWithinOriginalContainingType(
NamedTypeSymbol withinType,
NamedTypeSymbol originalContainingType)
{
Debug.Assert((object)withinType != null);
Debug.Assert((object)originalContainingType != null);
Debug.Assert(originalContainingType.IsDefinition);
// Walk up my parent chain and see if I eventually hit the owner. If so then I'm a
// nested type of that owner and I'm allowed access to everything inside of it.
var current = withinType.OriginalDefinition;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (current == (object)originalContainingType)
{
return true;
}
// NOTE(cyrusn): The container of an 'original' type is always original.
current = current.ContainingType;
}
return false;
}
/// <summary>
/// Determine if "type" inherits from or implements "baseType", ignoring constructed types, and dealing
/// only with original types.
/// </summary>
private static bool InheritsFromOrImplementsIgnoringConstruction(
this TypeSymbol type,
NamedTypeSymbol baseType,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert(type.IsDefinition);
Debug.Assert(baseType.IsDefinition);
PooledHashSet<NamedTypeSymbol> interfacesLookedAt = null;
ArrayBuilder<NamedTypeSymbol> baseInterfaces = null;
bool baseTypeIsInterface = baseType.IsInterface;
if (baseTypeIsInterface)
{
interfacesLookedAt = PooledHashSet<NamedTypeSymbol>.GetInstance();
baseInterfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance();
}
PooledHashSet<NamedTypeSymbol> visited = null;
var current = type;
bool result = false;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (baseTypeIsInterface == current.IsInterfaceType() &&
current == (object)baseType)
{
result = true;
break;
}
if (baseTypeIsInterface)
{
getBaseInterfaces(current, baseInterfaces, interfacesLookedAt, basesBeingResolved);
}
// NOTE(cyrusn): The base type of an 'original' type may not be 'original'. i.e.
// "class Goo : IBar<int>". We must map it back to the 'original' when as we walk up
// the base type hierarchy.
var next = current.GetNextBaseTypeNoUseSiteDiagnostics(basesBeingResolved, compilation, ref visited);
if ((object)next == null)
{
current = null;
}
else
{
current = (TypeSymbol)next.OriginalDefinition;
current.AddUseSiteInfo(ref useSiteInfo);
}
}
visited?.Free();
if (!result && baseTypeIsInterface)
{
Debug.Assert(!result);
while (baseInterfaces.Count != 0)
{
NamedTypeSymbol currentBase = baseInterfaces.Pop();
if (!currentBase.IsInterface)
{
continue;
}
Debug.Assert(currentBase.IsDefinition);
if (currentBase == (object)baseType)
{
result = true;
break;
}
getBaseInterfaces(currentBase, baseInterfaces, interfacesLookedAt, basesBeingResolved);
}
if (!result)
{
foreach (var candidate in interfacesLookedAt)
{
candidate.AddUseSiteInfo(ref useSiteInfo);
}
}
}
interfacesLookedAt?.Free();
baseInterfaces?.Free();
return result;
static void getBaseInterfaces(TypeSymbol derived, ArrayBuilder<NamedTypeSymbol> baseInterfaces, PooledHashSet<NamedTypeSymbol> interfacesLookedAt, ConsList<TypeSymbol> basesBeingResolved)
{
if (basesBeingResolved != null && basesBeingResolved.ContainsReference(derived))
{
return;
}
ImmutableArray<NamedTypeSymbol> declaredInterfaces;
switch (derived)
{
case TypeParameterSymbol typeParameter:
declaredInterfaces = typeParameter.AllEffectiveInterfacesNoUseSiteDiagnostics;
break;
case NamedTypeSymbol namedType:
declaredInterfaces = namedType.GetDeclaredInterfaces(basesBeingResolved);
break;
default:
declaredInterfaces = derived.InterfacesNoUseSiteDiagnostics(basesBeingResolved);
break;
}
foreach (var @interface in declaredInterfaces)
{
NamedTypeSymbol definition = @interface.OriginalDefinition;
if (interfacesLookedAt.Add(definition))
{
baseInterfaces.Add(definition);
}
}
}
}
/// <summary>
/// Does the assembly has internal accessibility to "toAssembly"?
/// </summary>
/// <param name="fromAssembly">The assembly wanting access.</param>
/// <param name="toAssembly">The assembly possibly providing symbols to be accessed.</param>
internal static bool HasInternalAccessTo(this AssemblySymbol fromAssembly, AssemblySymbol toAssembly)
{
if (Equals(fromAssembly, toAssembly))
{
return true;
}
if (fromAssembly.AreInternalsVisibleToThisAssembly(toAssembly))
{
return true;
}
// all interactive assemblies are friends of each other:
if (fromAssembly.IsInteractive && toAssembly.IsInteractive)
{
return true;
}
return false;
}
internal static ErrorCode GetProtectedMemberInSealedTypeError(NamedTypeSymbol containingType)
{
return containingType.TypeKind == TypeKind.Struct ? ErrorCode.ERR_ProtectedInStruct : ErrorCode.WRN_ProtectedInSealed;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Contains the code for determining C# accessibility rules.
/// </summary>
internal static class AccessCheck
{
/// <summary>
/// Checks if 'symbol' is accessible from within assembly 'within'.
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
AssemblySymbol within,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
bool failedThroughTypeCheck;
return IsSymbolAccessibleCore(symbol, within, null, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo);
}
/// <summary>
/// Checks if 'symbol' is accessible from within type 'within', with
/// an optional qualifier of type "throughTypeOpt".
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
NamedTypeSymbol within,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
TypeSymbol throughTypeOpt = null)
{
bool failedThroughTypeCheck;
return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo);
}
/// <summary>
/// Checks if 'symbol' is accessible from within type 'within', with
/// a qualifier of type "throughTypeOpt". Sets "failedThroughTypeCheck" to true
/// if it failed the "through type" check.
/// </summary>
public static bool IsSymbolAccessible(
Symbol symbol,
NamedTypeSymbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
return IsSymbolAccessibleCore(symbol, within, throughTypeOpt, out failedThroughTypeCheck, within.DeclaringCompilation, ref useSiteInfo, basesBeingResolved);
}
/// <summary>
/// Returns true if the symbol is effectively public or internal based on
/// the declared accessibility of the symbol and any containing symbols.
/// </summary>
internal static bool IsEffectivelyPublicOrInternal(Symbol symbol, out bool isInternal)
{
Debug.Assert(symbol is object);
switch (symbol.Kind)
{
case SymbolKind.NamedType:
case SymbolKind.Event:
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.Property:
break;
case SymbolKind.TypeParameter:
symbol = symbol.ContainingSymbol;
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
isInternal = false;
do
{
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
case Accessibility.Protected:
case Accessibility.ProtectedOrInternal:
break;
case Accessibility.Internal:
case Accessibility.ProtectedAndInternal:
isInternal = true;
break;
case Accessibility.Private:
return false;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility);
}
symbol = symbol.ContainingType;
}
while (symbol is object);
return true;
}
/// <summary>
/// Checks if 'symbol' is accessible from within 'within', which must be a NamedTypeSymbol
/// or an AssemblySymbol.
/// </summary>
/// <remarks>
/// Note that NamedTypeSymbol, if available, is the type that is associated with the binder
/// that found the 'symbol', not the inner-most type that contains the access to the
/// 'symbol'.
/// <para>
/// If 'symbol' is accessed off of an expression then 'throughTypeOpt' is the type of that
/// expression. This is needed to properly do protected access checks. Sets
/// "failedThroughTypeCheck" to true if this protected check failed.
/// </para>
/// <para>
/// This function is expected to be called a lot. As such, it avoids memory
/// allocations in the function itself (including not making any iterators). This means
/// that certain helper functions that could otherwise be called are inlined in this method to
/// prevent the overhead of returning collections or enumerators.
/// </para>
/// </remarks>
private static bool IsSymbolAccessibleCore(
Symbol symbol,
Symbol within, // must be assembly or named type symbol
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert((object)symbol != null);
Debug.Assert((object)within != null);
Debug.Assert(within.IsDefinition);
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
failedThroughTypeCheck = false;
switch (symbol.Kind)
{
case SymbolKind.ArrayType:
return IsSymbolAccessibleCore(((ArrayTypeSymbol)symbol).ElementType, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.PointerType:
return IsSymbolAccessibleCore(((PointerTypeSymbol)symbol).PointedAtType, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.NamedType:
return IsNamedTypeAccessible((NamedTypeSymbol)symbol, within, ref useSiteInfo, basesBeingResolved);
case SymbolKind.Alias:
return IsSymbolAccessibleCore(((AliasSymbol)symbol).Target, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.Discard:
return IsSymbolAccessibleCore(((DiscardSymbol)symbol).TypeWithAnnotations.Type, within, null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case SymbolKind.FunctionPointerType:
var funcPtr = (FunctionPointerTypeSymbol)symbol;
if (!IsSymbolAccessibleCore(funcPtr.Signature.ReturnType, within, throughTypeOpt: null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved))
{
return false;
}
foreach (var param in funcPtr.Signature.Parameters)
{
if (!IsSymbolAccessibleCore(param.Type, within, throughTypeOpt: null, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved))
{
return false;
}
}
return true;
case SymbolKind.ErrorType:
// Always assume that error types are accessible.
return true;
case SymbolKind.TypeParameter:
case SymbolKind.Parameter:
case SymbolKind.Local:
case SymbolKind.Label:
case SymbolKind.Namespace:
case SymbolKind.DynamicType:
case SymbolKind.Assembly:
case SymbolKind.NetModule:
case SymbolKind.RangeVariable:
case SymbolKind.Method when ((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction:
// These types of symbols are always accessible (if visible).
return true;
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
case SymbolKind.Field:
if (!symbol.RequiresInstanceReceiver())
{
// static members aren't accessed "through" an "instance" of any type. So we
// null out the "through" instance here. This ensures that we'll understand
// accessing protected statics properly.
throughTypeOpt = null;
}
return IsMemberAccessible(symbol.ContainingType, symbol.DeclaredAccessibility, within, throughTypeOpt, out failedThroughTypeCheck, compilation, ref useSiteInfo);
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
/// <summary>
/// Is the named type <paramref name="type"/> accessible from within <paramref name="within"/>,
/// which must be a named type or an assembly.
/// </summary>
private static bool IsNamedTypeAccessible(NamedTypeSymbol type, Symbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)type != null);
var compilation = within.DeclaringCompilation;
bool unused;
if (!type.IsDefinition)
{
// All type argument must be accessible.
var typeArgs = type.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
foreach (var typeArg in typeArgs)
{
// type parameters are always accessible, so don't check those (so common it's
// worth optimizing this).
if (typeArg.Type.Kind != SymbolKind.TypeParameter && !IsSymbolAccessibleCore(typeArg.Type, within, null, out unused, compilation, ref useSiteInfo, basesBeingResolved))
{
return false;
}
}
}
var containingType = type.ContainingType;
return (object)containingType == null
? IsNonNestedTypeAccessible(type.ContainingAssembly, type.DeclaredAccessibility, within)
: IsMemberAccessible(containingType, type.DeclaredAccessibility, within, null, out unused, compilation, ref useSiteInfo, basesBeingResolved);
}
/// <summary>
/// Is a top-level type with accessibility "declaredAccessibility" inside assembly "assembly"
/// accessible from "within", which must be a named type of an assembly.
/// </summary>
private static bool IsNonNestedTypeAccessible(
AssemblySymbol assembly,
Accessibility declaredAccessibility,
Symbol within)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)assembly != null);
switch (declaredAccessibility)
{
case Accessibility.NotApplicable:
case Accessibility.Public:
// Public symbols are always accessible from any context
return true;
case Accessibility.Private:
case Accessibility.Protected:
case Accessibility.ProtectedAndInternal:
// Shouldn't happen except in error cases.
return false;
case Accessibility.Internal:
case Accessibility.ProtectedOrInternal:
// within is typically a type
var withinType = within as NamedTypeSymbol;
var withinAssembly = (object)withinType != null ? withinType.ContainingAssembly : (AssemblySymbol)within;
// An internal type is accessible if we're in the same assembly or we have
// friend access to the assembly it was defined in.
return (object)withinAssembly == (object)assembly || withinAssembly.HasInternalAccessTo(assembly);
default:
throw ExceptionUtilities.UnexpectedValue(declaredAccessibility);
}
}
/// <summary>
/// Is a member with declared accessibility "declaredAccessibility" accessible from within
/// "within", which must be a named type or an assembly.
/// </summary>
private static bool IsMemberAccessible(
NamedTypeSymbol containingType, // the symbol's containing type
Accessibility declaredAccessibility,
Symbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
Debug.Assert((object)containingType != null);
failedThroughTypeCheck = false;
// easy case - members of containing type are accessible.
if ((object)containingType == (object)within)
{
return true;
}
// A nested symbol is only accessible to us if its container is accessible as well.
if (!IsNamedTypeAccessible(containingType, within, ref useSiteInfo, basesBeingResolved))
{
return false;
}
// public in accessible type is accessible
if (declaredAccessibility == Accessibility.Public)
{
return true;
}
return IsNonPublicMemberAccessible(
containingType,
declaredAccessibility,
within,
throughTypeOpt,
out failedThroughTypeCheck,
compilation,
ref useSiteInfo,
basesBeingResolved);
}
private static bool IsNonPublicMemberAccessible(
NamedTypeSymbol containingType, // the symbol's containing type
Accessibility declaredAccessibility,
Symbol within,
TypeSymbol throughTypeOpt,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
failedThroughTypeCheck = false;
var originalContainingType = containingType.OriginalDefinition;
var withinType = within as NamedTypeSymbol;
var withinAssembly = (object)withinType != null ? withinType.ContainingAssembly : (AssemblySymbol)within;
switch (declaredAccessibility)
{
case Accessibility.NotApplicable:
return true;
case Accessibility.Private:
// All expressions in the current submission (top-level or nested in a method or
// type) can access previous submission's private top-level members. Previous
// submissions are treated like outer classes for the current submission - the
// inner class can access private members of the outer class.
if (containingType.TypeKind == TypeKind.Submission)
{
return true;
}
// private members never accessible from outside a type.
return (object)withinType != null && IsPrivateSymbolAccessible(withinType, originalContainingType);
case Accessibility.Internal:
// An internal type is accessible if we're in the same assembly or we have
// friend access to the assembly it was defined in.
return withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly);
case Accessibility.ProtectedAndInternal:
if (!withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly))
{
// We require internal access. If we don't have it, then this symbol is
// definitely not accessible to us.
return false;
}
// We had internal access. Also have to make sure we have protected access.
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case Accessibility.ProtectedOrInternal:
if (withinAssembly.HasInternalAccessTo(containingType.ContainingAssembly))
{
// If we have internal access to this symbol, then that's sufficient. no
// need to do the complicated protected case.
return true;
}
// We don't have internal access. But if we have protected access then that's
// sufficient.
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
case Accessibility.Protected:
return IsProtectedSymbolAccessible(withinType, throughTypeOpt, originalContainingType, out failedThroughTypeCheck, compilation, ref useSiteInfo, basesBeingResolved);
default:
throw ExceptionUtilities.UnexpectedValue(declaredAccessibility);
}
}
/// <summary>
/// Is a protected symbol inside "originalContainingType" accessible from within "within",
/// which much be a named type or an assembly.
/// </summary>
private static bool IsProtectedSymbolAccessible(
NamedTypeSymbol withinType,
TypeSymbol throughTypeOpt,
NamedTypeSymbol originalContainingType,
out bool failedThroughTypeCheck,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
failedThroughTypeCheck = false;
// It is not an error to define protected member in a sealed Script class, it's just a
// warning. The member behaves like a private one - it is visible in all subsequent
// submissions.
if (originalContainingType.TypeKind == TypeKind.Submission)
{
return true;
}
if ((object)withinType == null)
{
// If we're not within a type, we can't access a protected symbol
return false;
}
// A protected symbol is accessible if we're (optionally nested) inside the type that it
// was defined in.
// It is helpful to think about 'protected' as *increasing* the
// accessibility domain of a private member, rather than *decreasing* that of a public
// member. Members are naturally private; the protected, internal and public access
// modifiers all increase the accessibility domain. Since private members are accessible
// to nested types, so are protected members.
// We do this check up front as it is very fast and easy to do.
if (IsNestedWithinOriginalContainingType(withinType, originalContainingType))
{
return true;
}
// Protected is really confusing. Check out 3.5.3 of the language spec "protected access
// for instance members" to see how it works. I actually got the code for this from
// LangCompiler::CheckAccessCore
{
var current = withinType.OriginalDefinition;
var originalThroughTypeOpt = (object)throughTypeOpt == null ? null : throughTypeOpt.OriginalDefinition as TypeSymbol;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (current.InheritsFromOrImplementsIgnoringConstruction(originalContainingType, compilation, ref useSiteInfo, basesBeingResolved))
{
// NOTE(cyrusn): We're continually walking up the 'throughType's inheritance
// chain. We could compute it up front and cache it in a set. However, we
// don't want to allocate memory in this function. Also, in practice
// inheritance chains should be very short. As such, it might actually be
// slower to create and check inside the set versus just walking the
// inheritance chain.
if ((object)originalThroughTypeOpt == null ||
originalThroughTypeOpt.InheritsFromOrImplementsIgnoringConstruction(current, compilation, ref useSiteInfo))
{
return true;
}
else
{
failedThroughTypeCheck = true;
}
}
// NOTE(cyrusn): The container of an original type is always original.
current = current.ContainingType;
}
}
return false;
}
private static bool IsPrivateSymbolAccessible(
Symbol within,
NamedTypeSymbol originalContainingType)
{
Debug.Assert(within is NamedTypeSymbol || within is AssemblySymbol);
var withinType = within as NamedTypeSymbol;
if ((object)withinType == null)
{
// If we're not within a type, we can't access a private symbol
return false;
}
// A private symbol is accessible if we're (optionally nested) inside the type that it
// was defined in.
return IsNestedWithinOriginalContainingType(withinType, originalContainingType);
}
/// <summary>
/// Is the type "withinType" nested within the original type "originalContainingType".
/// </summary>
private static bool IsNestedWithinOriginalContainingType(
NamedTypeSymbol withinType,
NamedTypeSymbol originalContainingType)
{
Debug.Assert((object)withinType != null);
Debug.Assert((object)originalContainingType != null);
Debug.Assert(originalContainingType.IsDefinition);
// Walk up my parent chain and see if I eventually hit the owner. If so then I'm a
// nested type of that owner and I'm allowed access to everything inside of it.
var current = withinType.OriginalDefinition;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (current == (object)originalContainingType)
{
return true;
}
// NOTE(cyrusn): The container of an 'original' type is always original.
current = current.ContainingType;
}
return false;
}
/// <summary>
/// Determine if "type" inherits from or implements "baseType", ignoring constructed types, and dealing
/// only with original types.
/// </summary>
private static bool InheritsFromOrImplementsIgnoringConstruction(
this TypeSymbol type,
NamedTypeSymbol baseType,
CSharpCompilation compilation,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
ConsList<TypeSymbol> basesBeingResolved = null)
{
Debug.Assert(type.IsDefinition);
Debug.Assert(baseType.IsDefinition);
PooledHashSet<NamedTypeSymbol> interfacesLookedAt = null;
ArrayBuilder<NamedTypeSymbol> baseInterfaces = null;
bool baseTypeIsInterface = baseType.IsInterface;
if (baseTypeIsInterface)
{
interfacesLookedAt = PooledHashSet<NamedTypeSymbol>.GetInstance();
baseInterfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance();
}
PooledHashSet<NamedTypeSymbol> visited = null;
var current = type;
bool result = false;
while ((object)current != null)
{
Debug.Assert(current.IsDefinition);
if (baseTypeIsInterface == current.IsInterfaceType() &&
current == (object)baseType)
{
result = true;
break;
}
if (baseTypeIsInterface)
{
getBaseInterfaces(current, baseInterfaces, interfacesLookedAt, basesBeingResolved);
}
// NOTE(cyrusn): The base type of an 'original' type may not be 'original'. i.e.
// "class Goo : IBar<int>". We must map it back to the 'original' when as we walk up
// the base type hierarchy.
var next = current.GetNextBaseTypeNoUseSiteDiagnostics(basesBeingResolved, compilation, ref visited);
if ((object)next == null)
{
current = null;
}
else
{
current = (TypeSymbol)next.OriginalDefinition;
current.AddUseSiteInfo(ref useSiteInfo);
}
}
visited?.Free();
if (!result && baseTypeIsInterface)
{
Debug.Assert(!result);
while (baseInterfaces.Count != 0)
{
NamedTypeSymbol currentBase = baseInterfaces.Pop();
if (!currentBase.IsInterface)
{
continue;
}
Debug.Assert(currentBase.IsDefinition);
if (currentBase == (object)baseType)
{
result = true;
break;
}
getBaseInterfaces(currentBase, baseInterfaces, interfacesLookedAt, basesBeingResolved);
}
if (!result)
{
foreach (var candidate in interfacesLookedAt)
{
candidate.AddUseSiteInfo(ref useSiteInfo);
}
}
}
interfacesLookedAt?.Free();
baseInterfaces?.Free();
return result;
static void getBaseInterfaces(TypeSymbol derived, ArrayBuilder<NamedTypeSymbol> baseInterfaces, PooledHashSet<NamedTypeSymbol> interfacesLookedAt, ConsList<TypeSymbol> basesBeingResolved)
{
if (basesBeingResolved != null && basesBeingResolved.ContainsReference(derived))
{
return;
}
ImmutableArray<NamedTypeSymbol> declaredInterfaces;
switch (derived)
{
case TypeParameterSymbol typeParameter:
declaredInterfaces = typeParameter.AllEffectiveInterfacesNoUseSiteDiagnostics;
break;
case NamedTypeSymbol namedType:
declaredInterfaces = namedType.GetDeclaredInterfaces(basesBeingResolved);
break;
default:
declaredInterfaces = derived.InterfacesNoUseSiteDiagnostics(basesBeingResolved);
break;
}
foreach (var @interface in declaredInterfaces)
{
NamedTypeSymbol definition = @interface.OriginalDefinition;
if (interfacesLookedAt.Add(definition))
{
baseInterfaces.Add(definition);
}
}
}
}
/// <summary>
/// Does the assembly has internal accessibility to "toAssembly"?
/// </summary>
/// <param name="fromAssembly">The assembly wanting access.</param>
/// <param name="toAssembly">The assembly possibly providing symbols to be accessed.</param>
internal static bool HasInternalAccessTo(this AssemblySymbol fromAssembly, AssemblySymbol toAssembly)
{
if (Equals(fromAssembly, toAssembly))
{
return true;
}
if (fromAssembly.AreInternalsVisibleToThisAssembly(toAssembly))
{
return true;
}
// all interactive assemblies are friends of each other:
if (fromAssembly.IsInteractive && toAssembly.IsInteractive)
{
return true;
}
return false;
}
internal static ErrorCode GetProtectedMemberInSealedTypeError(NamedTypeSymbol containingType)
{
return containingType.TypeKind == TypeKind.Struct ? ErrorCode.ERR_ProtectedInStruct : ErrorCode.WRN_ProtectedInSealed;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThrowKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ThrowKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ThrowKeywordRecommender()
: base(SyntaxKind.ThrowKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.IsStatementContext || context.IsGlobalStatementContext)
{
return true;
}
// void M() => throw
if (context.TargetToken.Kind() == SyntaxKind.EqualsGreaterThanToken)
{
return true;
}
// val ?? throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionQuestionToken)
{
return true;
}
// expr ? throw : ...
// expr ? ... : throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionToken ||
context.TargetToken.Kind() == SyntaxKind.ColonToken)
{
return context.TargetToken.Parent.Kind() == SyntaxKind.ConditionalExpression;
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ThrowKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public ThrowKeywordRecommender()
: base(SyntaxKind.ThrowKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
if (context.IsStatementContext || context.IsGlobalStatementContext)
{
return true;
}
// void M() => throw
if (context.TargetToken.Kind() == SyntaxKind.EqualsGreaterThanToken)
{
return true;
}
// val ?? throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionQuestionToken)
{
return true;
}
// expr ? throw : ...
// expr ? ... : throw
if (context.TargetToken.Kind() == SyntaxKind.QuestionToken ||
context.TargetToken.Kind() == SyntaxKind.ColonToken)
{
return context.TargetToken.Parent.Kind() == SyntaxKind.ConditionalExpression;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/TestUtilities/QuickInfo/ToolTipAssert.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities.QuickInfo
{
public static class ToolTipAssert
{
public static void EqualContent(object expected, object actual)
{
try
{
Assert.IsType(expected.GetType(), actual);
if (expected is ContainerElement containerElement)
{
EqualContainerElement(containerElement, (ContainerElement)actual);
return;
}
if (expected is ImageElement imageElement)
{
EqualImageElement(imageElement, (ImageElement)actual);
return;
}
if (expected is ClassifiedTextElement classifiedTextElement)
{
EqualClassifiedTextElement(classifiedTextElement, (ClassifiedTextElement)actual);
return;
}
if (expected is ClassifiedTextRun classifiedTextRun)
{
EqualClassifiedTextRun(classifiedTextRun, (ClassifiedTextRun)actual);
return;
}
throw ExceptionUtilities.Unreachable;
}
catch (Exception)
{
var renderedExpected = ContainerToString(expected);
var renderedActual = ContainerToString(actual);
AssertEx.EqualOrDiff(renderedExpected, renderedActual);
// This is not expected to be hit, but it will be hit if the difference cannot be detected within the diff
throw;
}
}
private static void EqualContainerElement(ContainerElement expected, ContainerElement actual)
{
Assert.Equal(expected.Style, actual.Style);
Assert.Equal(expected.Elements.Count(), actual.Elements.Count());
foreach (var (expectedElement, actualElement) in expected.Elements.Zip(actual.Elements, (expectedElement, actualElement) => (expectedElement, actualElement)))
{
EqualContent(expectedElement, actualElement);
}
}
private static void EqualImageElement(ImageElement expected, ImageElement actual)
{
Assert.Equal(expected.ImageId.Guid, actual.ImageId.Guid);
Assert.Equal(expected.ImageId.Id, actual.ImageId.Id);
Assert.Equal(expected.AutomationName, actual.AutomationName);
}
private static void EqualClassifiedTextElement(ClassifiedTextElement expected, ClassifiedTextElement actual)
{
Assert.Equal(expected.Runs.Count(), actual.Runs.Count());
foreach (var (expectedRun, actualRun) in expected.Runs.Zip(actual.Runs, (expectedRun, actualRun) => (expectedRun, actualRun)))
{
EqualClassifiedTextRun(expectedRun, actualRun);
}
}
private static void EqualClassifiedTextRun(ClassifiedTextRun expected, ClassifiedTextRun actual)
{
Assert.Equal(expected.ClassificationTypeName, actual.ClassificationTypeName);
Assert.Equal(expected.Text, actual.Text);
Assert.Equal(expected.Tooltip, actual.Tooltip);
Assert.Equal(expected.Style, actual.Style);
if (expected.NavigationAction is null)
{
Assert.Equal(expected.NavigationAction, actual.NavigationAction);
}
else if (expected.NavigationAction.Target is QuickInfoHyperLink hyperLink)
{
Assert.Same(expected.NavigationAction, hyperLink.NavigationAction);
var actualTarget = Assert.IsType<QuickInfoHyperLink>(actual.NavigationAction.Target);
Assert.Same(actual.NavigationAction, actualTarget.NavigationAction);
Assert.Equal(hyperLink, actualTarget);
}
else
{
// Cannot validate this navigation action
Assert.NotNull(actual.NavigationAction);
Assert.IsNotType<QuickInfoHyperLink>(actual.NavigationAction.Target);
}
}
private static string ContainerToString(object element)
{
var result = new StringBuilder();
ContainerToString(element, "", result);
return result.ToString();
}
private static void ContainerToString(object element, string indent, StringBuilder result)
{
result.Append($"{indent}New {element.GetType().Name}(");
if (element is ContainerElement container)
{
result.AppendLine();
indent += " ";
result.AppendLine($"{indent}{ContainerStyleToString(container.Style)},");
var elements = container.Elements.ToArray();
for (var i = 0; i < elements.Length; i++)
{
ContainerToString(elements[i], indent, result);
if (i < elements.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ImageElement image)
{
var guid = GetKnownImageGuid(image.ImageId.Guid);
var id = GetKnownImageId(image.ImageId.Id);
result.Append($"New {nameof(ImageId)}({guid}, {id}))");
return;
}
if (element is ClassifiedTextElement classifiedTextElement)
{
result.AppendLine();
indent += " ";
var runs = classifiedTextElement.Runs.ToArray();
for (var i = 0; i < runs.Length; i++)
{
ContainerToString(runs[i], indent, result);
if (i < runs.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ClassifiedTextRun classifiedTextRun)
{
var classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName);
result.Append($"{classification}, \"{classifiedTextRun.Text.Replace("\"", "\"\"")}\"");
if (classifiedTextRun.NavigationAction is object || !string.IsNullOrEmpty(classifiedTextRun.Tooltip))
{
var tooltip = classifiedTextRun.Tooltip is object ? $"\"{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}\"" : "Nothing";
if (classifiedTextRun.NavigationAction?.Target is QuickInfoHyperLink hyperLink)
{
result.Append($", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri(\"{hyperLink.Uri}\", UriKind.Absolute))");
}
else
{
result.Append(", navigationAction:=Sub() Return");
}
result.Append($", {tooltip}");
}
if (classifiedTextRun.Style != ClassifiedTextRunStyle.Plain)
{
result.Append($", {TextRunStyleToString(classifiedTextRun.Style)}");
}
result.Append(")");
return;
}
throw ExceptionUtilities.Unreachable;
}
private static string ContainerStyleToString(ContainerElementStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ContainerElementStyle)}.{value}"));
}
private static string TextRunStyleToString(ClassifiedTextRunStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ClassifiedTextRunStyle)}.{value}"));
}
private static string GetKnownClassification(string classification)
{
foreach (var field in typeof(ClassificationTypeNames).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as string;
if (value == classification)
return $"{nameof(ClassificationTypeNames)}.{field.Name}";
}
return $"\"{classification}\"";
}
private static string GetKnownImageGuid(Guid guid)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as Guid?;
if (value == guid)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return guid.ToString();
}
private static string GetKnownImageId(int id)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as int?;
if (value == id)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return id.ToString();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities.QuickInfo
{
public static class ToolTipAssert
{
public static void EqualContent(object expected, object actual)
{
try
{
Assert.IsType(expected.GetType(), actual);
if (expected is ContainerElement containerElement)
{
EqualContainerElement(containerElement, (ContainerElement)actual);
return;
}
if (expected is ImageElement imageElement)
{
EqualImageElement(imageElement, (ImageElement)actual);
return;
}
if (expected is ClassifiedTextElement classifiedTextElement)
{
EqualClassifiedTextElement(classifiedTextElement, (ClassifiedTextElement)actual);
return;
}
if (expected is ClassifiedTextRun classifiedTextRun)
{
EqualClassifiedTextRun(classifiedTextRun, (ClassifiedTextRun)actual);
return;
}
throw ExceptionUtilities.Unreachable;
}
catch (Exception)
{
var renderedExpected = ContainerToString(expected);
var renderedActual = ContainerToString(actual);
AssertEx.EqualOrDiff(renderedExpected, renderedActual);
// This is not expected to be hit, but it will be hit if the difference cannot be detected within the diff
throw;
}
}
private static void EqualContainerElement(ContainerElement expected, ContainerElement actual)
{
Assert.Equal(expected.Style, actual.Style);
Assert.Equal(expected.Elements.Count(), actual.Elements.Count());
foreach (var (expectedElement, actualElement) in expected.Elements.Zip(actual.Elements, (expectedElement, actualElement) => (expectedElement, actualElement)))
{
EqualContent(expectedElement, actualElement);
}
}
private static void EqualImageElement(ImageElement expected, ImageElement actual)
{
Assert.Equal(expected.ImageId.Guid, actual.ImageId.Guid);
Assert.Equal(expected.ImageId.Id, actual.ImageId.Id);
Assert.Equal(expected.AutomationName, actual.AutomationName);
}
private static void EqualClassifiedTextElement(ClassifiedTextElement expected, ClassifiedTextElement actual)
{
Assert.Equal(expected.Runs.Count(), actual.Runs.Count());
foreach (var (expectedRun, actualRun) in expected.Runs.Zip(actual.Runs, (expectedRun, actualRun) => (expectedRun, actualRun)))
{
EqualClassifiedTextRun(expectedRun, actualRun);
}
}
private static void EqualClassifiedTextRun(ClassifiedTextRun expected, ClassifiedTextRun actual)
{
Assert.Equal(expected.ClassificationTypeName, actual.ClassificationTypeName);
Assert.Equal(expected.Text, actual.Text);
Assert.Equal(expected.Tooltip, actual.Tooltip);
Assert.Equal(expected.Style, actual.Style);
if (expected.NavigationAction is null)
{
Assert.Equal(expected.NavigationAction, actual.NavigationAction);
}
else if (expected.NavigationAction.Target is QuickInfoHyperLink hyperLink)
{
Assert.Same(expected.NavigationAction, hyperLink.NavigationAction);
var actualTarget = Assert.IsType<QuickInfoHyperLink>(actual.NavigationAction.Target);
Assert.Same(actual.NavigationAction, actualTarget.NavigationAction);
Assert.Equal(hyperLink, actualTarget);
}
else
{
// Cannot validate this navigation action
Assert.NotNull(actual.NavigationAction);
Assert.IsNotType<QuickInfoHyperLink>(actual.NavigationAction.Target);
}
}
private static string ContainerToString(object element)
{
var result = new StringBuilder();
ContainerToString(element, "", result);
return result.ToString();
}
private static void ContainerToString(object element, string indent, StringBuilder result)
{
result.Append($"{indent}New {element.GetType().Name}(");
if (element is ContainerElement container)
{
result.AppendLine();
indent += " ";
result.AppendLine($"{indent}{ContainerStyleToString(container.Style)},");
var elements = container.Elements.ToArray();
for (var i = 0; i < elements.Length; i++)
{
ContainerToString(elements[i], indent, result);
if (i < elements.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ImageElement image)
{
var guid = GetKnownImageGuid(image.ImageId.Guid);
var id = GetKnownImageId(image.ImageId.Id);
result.Append($"New {nameof(ImageId)}({guid}, {id}))");
return;
}
if (element is ClassifiedTextElement classifiedTextElement)
{
result.AppendLine();
indent += " ";
var runs = classifiedTextElement.Runs.ToArray();
for (var i = 0; i < runs.Length; i++)
{
ContainerToString(runs[i], indent, result);
if (i < runs.Length - 1)
result.AppendLine(",");
else
result.Append(")");
}
return;
}
if (element is ClassifiedTextRun classifiedTextRun)
{
var classification = GetKnownClassification(classifiedTextRun.ClassificationTypeName);
result.Append($"{classification}, \"{classifiedTextRun.Text.Replace("\"", "\"\"")}\"");
if (classifiedTextRun.NavigationAction is object || !string.IsNullOrEmpty(classifiedTextRun.Tooltip))
{
var tooltip = classifiedTextRun.Tooltip is object ? $"\"{classifiedTextRun.Tooltip.Replace("\"", "\"\"")}\"" : "Nothing";
if (classifiedTextRun.NavigationAction?.Target is QuickInfoHyperLink hyperLink)
{
result.Append($", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri(\"{hyperLink.Uri}\", UriKind.Absolute))");
}
else
{
result.Append(", navigationAction:=Sub() Return");
}
result.Append($", {tooltip}");
}
if (classifiedTextRun.Style != ClassifiedTextRunStyle.Plain)
{
result.Append($", {TextRunStyleToString(classifiedTextRun.Style)}");
}
result.Append(")");
return;
}
throw ExceptionUtilities.Unreachable;
}
private static string ContainerStyleToString(ContainerElementStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ContainerElementStyle)}.{value}"));
}
private static string TextRunStyleToString(ClassifiedTextRunStyle style)
{
var stringValue = style.ToString();
return string.Join(" Or ", stringValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(value => $"{nameof(ClassifiedTextRunStyle)}.{value}"));
}
private static string GetKnownClassification(string classification)
{
foreach (var field in typeof(ClassificationTypeNames).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as string;
if (value == classification)
return $"{nameof(ClassificationTypeNames)}.{field.Name}";
}
return $"\"{classification}\"";
}
private static string GetKnownImageGuid(Guid guid)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as Guid?;
if (value == guid)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return guid.ToString();
}
private static string GetKnownImageId(int id)
{
foreach (var field in typeof(KnownImageIds).GetFields())
{
if (!field.IsStatic)
continue;
var value = field.GetValue(null) as int?;
if (value == id)
return $"{nameof(KnownImageIds)}.{field.Name}";
}
return id.ToString();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Remote/Core/ServiceHubRemoteHostClient.ConnectionPools.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class ServiceHubRemoteHostClient
{
public delegate Task<RemoteServiceConnection> ConnectionFactory(RemoteServiceName serviceName, IPooledConnectionReclamation poolReclamation, CancellationToken cancellationToken);
internal sealed class ConnectionPools : IDisposable
{
private sealed class Pool : IPooledConnectionReclamation
{
private readonly ConcurrentQueue<JsonRpcConnection> _queue;
private readonly ConnectionPools _owner;
public Pool(ConnectionPools connectionPools)
{
_queue = new ConcurrentQueue<JsonRpcConnection>();
_owner = connectionPools;
}
public void Return(JsonRpcConnection connection)
=> _owner.Free(_queue, connection);
public bool TryAcquire([NotNullWhen(true)] out JsonRpcConnection? connection)
{
if (_queue.TryDequeue(out connection))
{
connection.SetPoolReclamation(this);
return true;
}
return false;
}
internal void DisposeConnections()
{
// Use TryDequeue instead of TryAcquire to ensure disposal doesn't just return the collection to the
// pool.
while (_queue.TryDequeue(out var connection))
{
connection.Dispose();
}
}
}
private readonly ConnectionFactory _connectionFactory;
private readonly ReaderWriterLockSlim _shutdownLock;
private readonly int _capacityPerService;
// keyed to serviceName. each connection is for specific service such as CodeAnalysisService
private readonly ConcurrentDictionary<RemoteServiceName, Pool> _pools;
private bool _isDisposed;
public ConnectionPools(ConnectionFactory connectionFactory, int capacity)
{
_connectionFactory = connectionFactory;
_capacityPerService = capacity;
// initial value 4 is chosen to stop concurrent dictionary creating too many locks.
// and big enough for all our services such as codeanalysis, remotehost, snapshot and etc services
_pools = new ConcurrentDictionary<RemoteServiceName, Pool>(concurrencyLevel: 4, capacity: 4);
_shutdownLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
}
public async Task<RemoteServiceConnection> GetOrCreateConnectionAsync(RemoteServiceName serviceName, CancellationToken cancellationToken)
{
var pool = _pools.GetOrAdd(serviceName, _ => new Pool(this));
if (pool.TryAcquire(out var connection))
{
return connection;
}
return await _connectionFactory(serviceName, pool, cancellationToken).ConfigureAwait(false);
}
internal void Free(ConcurrentQueue<JsonRpcConnection> pool, JsonRpcConnection connection)
{
using (_shutdownLock.DisposableRead())
{
// There is a race between checking the current pool capacity in the condition and
// and queueing connections to the pool in the else branch.
// The amount of pooled connections may thus exceed the capacity at times,
// or some connections might not end up returned into the pool and reused.
if (_isDisposed || pool.Count >= _capacityPerService)
{
connection.Dispose();
}
else
{
pool.Enqueue(connection);
}
}
}
public void Dispose()
{
using (_shutdownLock.DisposableWrite())
{
_isDisposed = true;
foreach (var (_, pool) in _pools)
{
pool.DisposeConnections();
}
_pools.Clear();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class ServiceHubRemoteHostClient
{
public delegate Task<RemoteServiceConnection> ConnectionFactory(RemoteServiceName serviceName, IPooledConnectionReclamation poolReclamation, CancellationToken cancellationToken);
internal sealed class ConnectionPools : IDisposable
{
private sealed class Pool : IPooledConnectionReclamation
{
private readonly ConcurrentQueue<JsonRpcConnection> _queue;
private readonly ConnectionPools _owner;
public Pool(ConnectionPools connectionPools)
{
_queue = new ConcurrentQueue<JsonRpcConnection>();
_owner = connectionPools;
}
public void Return(JsonRpcConnection connection)
=> _owner.Free(_queue, connection);
public bool TryAcquire([NotNullWhen(true)] out JsonRpcConnection? connection)
{
if (_queue.TryDequeue(out connection))
{
connection.SetPoolReclamation(this);
return true;
}
return false;
}
internal void DisposeConnections()
{
// Use TryDequeue instead of TryAcquire to ensure disposal doesn't just return the collection to the
// pool.
while (_queue.TryDequeue(out var connection))
{
connection.Dispose();
}
}
}
private readonly ConnectionFactory _connectionFactory;
private readonly ReaderWriterLockSlim _shutdownLock;
private readonly int _capacityPerService;
// keyed to serviceName. each connection is for specific service such as CodeAnalysisService
private readonly ConcurrentDictionary<RemoteServiceName, Pool> _pools;
private bool _isDisposed;
public ConnectionPools(ConnectionFactory connectionFactory, int capacity)
{
_connectionFactory = connectionFactory;
_capacityPerService = capacity;
// initial value 4 is chosen to stop concurrent dictionary creating too many locks.
// and big enough for all our services such as codeanalysis, remotehost, snapshot and etc services
_pools = new ConcurrentDictionary<RemoteServiceName, Pool>(concurrencyLevel: 4, capacity: 4);
_shutdownLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
}
public async Task<RemoteServiceConnection> GetOrCreateConnectionAsync(RemoteServiceName serviceName, CancellationToken cancellationToken)
{
var pool = _pools.GetOrAdd(serviceName, _ => new Pool(this));
if (pool.TryAcquire(out var connection))
{
return connection;
}
return await _connectionFactory(serviceName, pool, cancellationToken).ConfigureAwait(false);
}
internal void Free(ConcurrentQueue<JsonRpcConnection> pool, JsonRpcConnection connection)
{
using (_shutdownLock.DisposableRead())
{
// There is a race between checking the current pool capacity in the condition and
// and queueing connections to the pool in the else branch.
// The amount of pooled connections may thus exceed the capacity at times,
// or some connections might not end up returned into the pool and reused.
if (_isDisposed || pool.Count >= _capacityPerService)
{
connection.Dispose();
}
else
{
pool.Enqueue(connection);
}
}
}
public void Dispose()
{
using (_shutdownLock.DisposableWrite())
{
_isDisposed = true;
foreach (var (_, pool) in _pools)
{
pool.DisposeConnections();
}
_pools.Clear();
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/CodeLens/CSharpCodeLensDisplayInfoService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CodeLens;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeLens
{
[ExportLanguageService(typeof(ICodeLensDisplayInfoService), LanguageNames.CSharp), Shared]
internal sealed class CSharpCodeLensDisplayInfoService : ICodeLensDisplayInfoService
{
private static readonly SymbolDisplayFormat Format =
SymbolDisplayFormat.CSharpErrorMessageFormat.RemoveMemberOptions(
SymbolDisplayMemberOptions.IncludeExplicitInterface);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCodeLensDisplayInfoService()
{
}
/// <summary>
/// Returns the node that should be displayed
/// </summary>
public SyntaxNode GetDisplayNode(SyntaxNode node)
{
while (true)
{
switch (node.Kind())
{
// LocalDeclarations do not have symbols themselves, you need a variable declarator
case SyntaxKind.LocalDeclarationStatement:
var localDeclarationNode = (LocalDeclarationStatementSyntax)node;
node = localDeclarationNode.Declaration.Variables.FirstOrDefault();
continue;
// Field and event declarations do not have symbols themselves, you need a variable declarator
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
var fieldNode = (BaseFieldDeclarationSyntax)node;
node = fieldNode.Declaration.Variables.FirstOrDefault();
continue;
// Variable is a field without access modifier. Parent is FieldDeclaration
case SyntaxKind.VariableDeclaration:
node = node.Parent;
continue;
// Built in types
case SyntaxKind.PredefinedType:
node = node.Parent;
continue;
case SyntaxKind.MultiLineDocumentationCommentTrivia:
case SyntaxKind.SingleLineDocumentationCommentTrivia:
// For DocumentationCommentTrivia node, node.Parent is null. Obtain parent through ParentTrivia.Token
if (node.IsStructuredTrivia)
{
var structuredTriviaSyntax = (StructuredTriviaSyntax)node;
node = structuredTriviaSyntax.ParentTrivia.Token.Parent;
continue;
}
return null;
default:
return node;
}
}
}
/// <summary>
/// Gets the DisplayName for the given node.
/// </summary>
public string GetDisplayName(SemanticModel semanticModel, SyntaxNode node)
{
if (node == null)
{
return FeaturesResources.paren_Unknown_paren;
}
if (CSharpSyntaxFacts.Instance.IsGlobalAssemblyAttribute(node))
{
return "assembly: " + node.ConvertToSingleLine();
}
// Don't discriminate between getters and setters for indexers
if (node.Parent.IsKind(SyntaxKind.AccessorList) &&
node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration))
{
return GetDisplayName(semanticModel, node.Parent.Parent);
}
switch (node.Kind())
{
case SyntaxKind.ConstructorDeclaration:
{
// The constructor's name will be the name of the class, not ctor like we want
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var openParenIndex = displayName.IndexOf('(');
var lastDotBeforeOpenParenIndex = displayName.LastIndexOf('.', openParenIndex, openParenIndex);
var constructorName = symbol.IsStatic ? "cctor" : "ctor";
return displayName.Substring(0, lastDotBeforeOpenParenIndex + 1) +
constructorName +
displayName.Substring(openParenIndex);
}
case SyntaxKind.IndexerDeclaration:
{
// The name will be "namespace.class.this[type] - we want "namespace.class[type] Indexer"
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var openBracketIndex = displayName.IndexOf('[');
var lastDotBeforeOpenBracketIndex = displayName.LastIndexOf('.', openBracketIndex, openBracketIndex);
return displayName.Substring(0, lastDotBeforeOpenBracketIndex) +
displayName.Substring(openBracketIndex) +
" Indexer";
}
case SyntaxKind.OperatorDeclaration:
{
// The name will be "namespace.class.operator +(type)" - we want namespace.class.+(type) Operator
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var spaceIndex = displayName.IndexOf(' ');
var lastDotBeforeSpaceIndex = displayName.LastIndexOf('.', spaceIndex, spaceIndex);
return displayName.Substring(0, lastDotBeforeSpaceIndex + 1) +
displayName.Substring(spaceIndex + 1) +
" Operator";
}
case SyntaxKind.ConversionOperatorDeclaration:
{
// The name will be "namespace.class.operator +(type)" - we want namespace.class.+(type) Operator
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var firstSpaceIndex = displayName.IndexOf(' ');
var secondSpaceIndex = displayName.IndexOf(' ', firstSpaceIndex + 1);
var lastDotBeforeSpaceIndex = displayName.LastIndexOf('.', firstSpaceIndex, firstSpaceIndex);
return displayName.Substring(0, lastDotBeforeSpaceIndex + 1) +
displayName.Substring(secondSpaceIndex + 1) +
" Operator";
}
case SyntaxKind.UsingDirective:
{
// We want to see usings formatted as simply "Using", prefaced by the namespace they are in
var enclosingScopeString = GetEnclosingScopeString(node, semanticModel, Format);
return string.IsNullOrEmpty(enclosingScopeString) ? "Using" : enclosingScopeString + " Using";
}
case SyntaxKind.ExternAliasDirective:
{
// We want to see aliases formatted as "Alias", prefaced by their enclosing scope, if any
var enclosingScopeString = GetEnclosingScopeString(node, semanticModel, Format);
return string.IsNullOrEmpty(enclosingScopeString) ? "Alias" : enclosingScopeString + " Alias";
}
default:
{
var symbol = semanticModel.GetDeclaredSymbol(node);
return symbol != null ? symbol.ToDisplayString(Format) : FeaturesResources.paren_Unknown_paren;
}
}
}
private static string GetEnclosingScopeString(SyntaxNode node, SemanticModel semanticModel, SymbolDisplayFormat symbolDisplayFormat)
{
var scopeNode = node;
while (scopeNode != null && !SyntaxFacts.IsNamespaceMemberDeclaration(scopeNode.Kind()))
{
scopeNode = scopeNode.Parent;
}
if (scopeNode == null)
{
return null;
}
var scopeSymbol = semanticModel.GetDeclaredSymbol(scopeNode);
return scopeSymbol.ToDisplayString(symbolDisplayFormat);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CodeLens;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeLens
{
[ExportLanguageService(typeof(ICodeLensDisplayInfoService), LanguageNames.CSharp), Shared]
internal sealed class CSharpCodeLensDisplayInfoService : ICodeLensDisplayInfoService
{
private static readonly SymbolDisplayFormat Format =
SymbolDisplayFormat.CSharpErrorMessageFormat.RemoveMemberOptions(
SymbolDisplayMemberOptions.IncludeExplicitInterface);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCodeLensDisplayInfoService()
{
}
/// <summary>
/// Returns the node that should be displayed
/// </summary>
public SyntaxNode GetDisplayNode(SyntaxNode node)
{
while (true)
{
switch (node.Kind())
{
// LocalDeclarations do not have symbols themselves, you need a variable declarator
case SyntaxKind.LocalDeclarationStatement:
var localDeclarationNode = (LocalDeclarationStatementSyntax)node;
node = localDeclarationNode.Declaration.Variables.FirstOrDefault();
continue;
// Field and event declarations do not have symbols themselves, you need a variable declarator
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
var fieldNode = (BaseFieldDeclarationSyntax)node;
node = fieldNode.Declaration.Variables.FirstOrDefault();
continue;
// Variable is a field without access modifier. Parent is FieldDeclaration
case SyntaxKind.VariableDeclaration:
node = node.Parent;
continue;
// Built in types
case SyntaxKind.PredefinedType:
node = node.Parent;
continue;
case SyntaxKind.MultiLineDocumentationCommentTrivia:
case SyntaxKind.SingleLineDocumentationCommentTrivia:
// For DocumentationCommentTrivia node, node.Parent is null. Obtain parent through ParentTrivia.Token
if (node.IsStructuredTrivia)
{
var structuredTriviaSyntax = (StructuredTriviaSyntax)node;
node = structuredTriviaSyntax.ParentTrivia.Token.Parent;
continue;
}
return null;
default:
return node;
}
}
}
/// <summary>
/// Gets the DisplayName for the given node.
/// </summary>
public string GetDisplayName(SemanticModel semanticModel, SyntaxNode node)
{
if (node == null)
{
return FeaturesResources.paren_Unknown_paren;
}
if (CSharpSyntaxFacts.Instance.IsGlobalAssemblyAttribute(node))
{
return "assembly: " + node.ConvertToSingleLine();
}
// Don't discriminate between getters and setters for indexers
if (node.Parent.IsKind(SyntaxKind.AccessorList) &&
node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration))
{
return GetDisplayName(semanticModel, node.Parent.Parent);
}
switch (node.Kind())
{
case SyntaxKind.ConstructorDeclaration:
{
// The constructor's name will be the name of the class, not ctor like we want
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var openParenIndex = displayName.IndexOf('(');
var lastDotBeforeOpenParenIndex = displayName.LastIndexOf('.', openParenIndex, openParenIndex);
var constructorName = symbol.IsStatic ? "cctor" : "ctor";
return displayName.Substring(0, lastDotBeforeOpenParenIndex + 1) +
constructorName +
displayName.Substring(openParenIndex);
}
case SyntaxKind.IndexerDeclaration:
{
// The name will be "namespace.class.this[type] - we want "namespace.class[type] Indexer"
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var openBracketIndex = displayName.IndexOf('[');
var lastDotBeforeOpenBracketIndex = displayName.LastIndexOf('.', openBracketIndex, openBracketIndex);
return displayName.Substring(0, lastDotBeforeOpenBracketIndex) +
displayName.Substring(openBracketIndex) +
" Indexer";
}
case SyntaxKind.OperatorDeclaration:
{
// The name will be "namespace.class.operator +(type)" - we want namespace.class.+(type) Operator
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var spaceIndex = displayName.IndexOf(' ');
var lastDotBeforeSpaceIndex = displayName.LastIndexOf('.', spaceIndex, spaceIndex);
return displayName.Substring(0, lastDotBeforeSpaceIndex + 1) +
displayName.Substring(spaceIndex + 1) +
" Operator";
}
case SyntaxKind.ConversionOperatorDeclaration:
{
// The name will be "namespace.class.operator +(type)" - we want namespace.class.+(type) Operator
var symbol = semanticModel.GetDeclaredSymbol(node);
var displayName = symbol.ToDisplayString(Format);
var firstSpaceIndex = displayName.IndexOf(' ');
var secondSpaceIndex = displayName.IndexOf(' ', firstSpaceIndex + 1);
var lastDotBeforeSpaceIndex = displayName.LastIndexOf('.', firstSpaceIndex, firstSpaceIndex);
return displayName.Substring(0, lastDotBeforeSpaceIndex + 1) +
displayName.Substring(secondSpaceIndex + 1) +
" Operator";
}
case SyntaxKind.UsingDirective:
{
// We want to see usings formatted as simply "Using", prefaced by the namespace they are in
var enclosingScopeString = GetEnclosingScopeString(node, semanticModel, Format);
return string.IsNullOrEmpty(enclosingScopeString) ? "Using" : enclosingScopeString + " Using";
}
case SyntaxKind.ExternAliasDirective:
{
// We want to see aliases formatted as "Alias", prefaced by their enclosing scope, if any
var enclosingScopeString = GetEnclosingScopeString(node, semanticModel, Format);
return string.IsNullOrEmpty(enclosingScopeString) ? "Alias" : enclosingScopeString + " Alias";
}
default:
{
var symbol = semanticModel.GetDeclaredSymbol(node);
return symbol != null ? symbol.ToDisplayString(Format) : FeaturesResources.paren_Unknown_paren;
}
}
}
private static string GetEnclosingScopeString(SyntaxNode node, SemanticModel semanticModel, SymbolDisplayFormat symbolDisplayFormat)
{
var scopeNode = node;
while (scopeNode != null && !SyntaxFacts.IsNamespaceMemberDeclaration(scopeNode.Kind()))
{
scopeNode = scopeNode.Parent;
}
if (scopeNode == null)
{
return null;
}
var scopeSymbol = semanticModel.GetDeclaredSymbol(scopeNode);
return scopeSymbol.ToDisplayString(symbolDisplayFormat);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/CodeAnalysisTest/Collections/BoxesTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class BoxesTest
{
[Fact]
public void AllBoxesTest()
{
// Boolean
Assert.Same(Boxes.Box(true), Boxes.Box(true));
Assert.Same(Boxes.Box(false), Boxes.Box(false));
Assert.NotSame(Boxes.Box(true), Boxes.Box(false));
// Byte
Assert.Same(Boxes.Box((byte)0), Boxes.Box((byte)0));
Assert.NotSame(Boxes.Box((byte)3), Boxes.Box((byte)3));
// SByte
Assert.Same(Boxes.Box((sbyte)0), Boxes.Box((sbyte)0));
Assert.NotSame(Boxes.Box((sbyte)3), Boxes.Box((sbyte)3));
// Int16
Assert.Same(Boxes.Box((short)0), Boxes.Box((short)0));
Assert.NotSame(Boxes.Box((short)3), Boxes.Box((short)3));
// UInt16
Assert.Same(Boxes.Box((ushort)0), Boxes.Box((ushort)0));
Assert.NotSame(Boxes.Box((ushort)3), Boxes.Box((ushort)3));
// Int32
Assert.Same(Boxes.Box(0), Boxes.Box(0));
Assert.Same(Boxes.Box(1), Boxes.Box(1));
Assert.Same(Boxes.BoxedInt32Zero, Boxes.Box(0));
Assert.Same(Boxes.BoxedInt32One, Boxes.Box(1));
Assert.NotSame(Boxes.Box(3), Boxes.Box(3));
// UInt32
Assert.Same(Boxes.Box(0u), Boxes.Box(0u));
Assert.NotSame(Boxes.Box(3u), Boxes.Box(3u));
// Int64
Assert.Same(Boxes.Box(0L), Boxes.Box(0L));
Assert.NotSame(Boxes.Box(3L), Boxes.Box(3L));
// UInt64
Assert.Same(Boxes.Box(0UL), Boxes.Box(0UL));
Assert.NotSame(Boxes.Box(3UL), Boxes.Box(3UL));
// Single
Assert.Same(Boxes.Box(0.0f), Boxes.Box(0.0f));
Assert.NotSame(Boxes.Box(0.0f), Boxes.Box(-0.0f));
Assert.NotSame(Boxes.Box(1.0f), Boxes.Box(1.0f));
// Double
Assert.Same(Boxes.Box(0.0), Boxes.Box(0.0));
Assert.NotSame(Boxes.Box(0.0), Boxes.Box(-0.0));
Assert.NotSame(Boxes.Box(1.0), Boxes.Box(1.0));
// Decimal
Assert.Same(Boxes.Box(decimal.Zero), Boxes.Box(0m));
Assert.NotSame(Boxes.Box(0m), Boxes.Box(decimal.Negate(0m)));
decimal strangeDecimalZero = new decimal(0, 0, 0, false, 10);
Assert.Equal(decimal.Zero, strangeDecimalZero);
Assert.NotSame(Boxes.Box(decimal.Zero), Boxes.Box(strangeDecimalZero));
// Char
Assert.Same(Boxes.Box('\0'), Boxes.Box('\0'));
Assert.Same(Boxes.Box('*'), Boxes.Box('*'));
Assert.Same(Boxes.Box('0'), Boxes.Box('0'));
Assert.NotSame(Boxes.Box('\u1234'), Boxes.Box('\u1234')); // non ASCII
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public class BoxesTest
{
[Fact]
public void AllBoxesTest()
{
// Boolean
Assert.Same(Boxes.Box(true), Boxes.Box(true));
Assert.Same(Boxes.Box(false), Boxes.Box(false));
Assert.NotSame(Boxes.Box(true), Boxes.Box(false));
// Byte
Assert.Same(Boxes.Box((byte)0), Boxes.Box((byte)0));
Assert.NotSame(Boxes.Box((byte)3), Boxes.Box((byte)3));
// SByte
Assert.Same(Boxes.Box((sbyte)0), Boxes.Box((sbyte)0));
Assert.NotSame(Boxes.Box((sbyte)3), Boxes.Box((sbyte)3));
// Int16
Assert.Same(Boxes.Box((short)0), Boxes.Box((short)0));
Assert.NotSame(Boxes.Box((short)3), Boxes.Box((short)3));
// UInt16
Assert.Same(Boxes.Box((ushort)0), Boxes.Box((ushort)0));
Assert.NotSame(Boxes.Box((ushort)3), Boxes.Box((ushort)3));
// Int32
Assert.Same(Boxes.Box(0), Boxes.Box(0));
Assert.Same(Boxes.Box(1), Boxes.Box(1));
Assert.Same(Boxes.BoxedInt32Zero, Boxes.Box(0));
Assert.Same(Boxes.BoxedInt32One, Boxes.Box(1));
Assert.NotSame(Boxes.Box(3), Boxes.Box(3));
// UInt32
Assert.Same(Boxes.Box(0u), Boxes.Box(0u));
Assert.NotSame(Boxes.Box(3u), Boxes.Box(3u));
// Int64
Assert.Same(Boxes.Box(0L), Boxes.Box(0L));
Assert.NotSame(Boxes.Box(3L), Boxes.Box(3L));
// UInt64
Assert.Same(Boxes.Box(0UL), Boxes.Box(0UL));
Assert.NotSame(Boxes.Box(3UL), Boxes.Box(3UL));
// Single
Assert.Same(Boxes.Box(0.0f), Boxes.Box(0.0f));
Assert.NotSame(Boxes.Box(0.0f), Boxes.Box(-0.0f));
Assert.NotSame(Boxes.Box(1.0f), Boxes.Box(1.0f));
// Double
Assert.Same(Boxes.Box(0.0), Boxes.Box(0.0));
Assert.NotSame(Boxes.Box(0.0), Boxes.Box(-0.0));
Assert.NotSame(Boxes.Box(1.0), Boxes.Box(1.0));
// Decimal
Assert.Same(Boxes.Box(decimal.Zero), Boxes.Box(0m));
Assert.NotSame(Boxes.Box(0m), Boxes.Box(decimal.Negate(0m)));
decimal strangeDecimalZero = new decimal(0, 0, 0, false, 10);
Assert.Equal(decimal.Zero, strangeDecimalZero);
Assert.NotSame(Boxes.Box(decimal.Zero), Boxes.Box(strangeDecimalZero));
// Char
Assert.Same(Boxes.Box('\0'), Boxes.Box('\0'));
Assert.Same(Boxes.Box('*'), Boxes.Box('*'));
Assert.Same(Boxes.Box('0'), Boxes.Box('0'));
Assert.NotSame(Boxes.Box('\u1234'), Boxes.Box('\u1234')); // non ASCII
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/NodeValidators.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
//test
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class NodeValidators
{
#region Verifiers
internal static void PointerNameVerification(ExpressionSyntax nameTree, string name)
{
Assert.IsType<PointerTypeSyntax>(nameTree);
var pointerName = nameTree as PointerTypeSyntax;
Assert.Equal(pointerName.ElementType.ToString(), name);
}
internal static void PredefinedNameVerification(ExpressionSyntax nameTree, string typeName)
{
Assert.IsType<PredefinedTypeSyntax>(nameTree);
var predefName = nameTree as PredefinedTypeSyntax;
Assert.Equal(predefName.ToString(), typeName);
}
internal static void ArrayNameVerification(ExpressionSyntax nameTree, string arrayName, int numRanks)
{
Assert.IsType<ArrayTypeSyntax>(nameTree);
var arrayType = nameTree as ArrayTypeSyntax;
Assert.Equal(arrayType.ElementType.ToString(), arrayName);
Assert.Equal(arrayType.RankSpecifiers.Count(), numRanks);
}
internal static void AliasedNameVerification(ExpressionSyntax nameTree, string alias, string name)
{
// Verification of the change
Assert.IsType<AliasQualifiedNameSyntax>(nameTree);
var aliasName = nameTree as AliasQualifiedNameSyntax;
Assert.Equal(aliasName.Alias.ToString(), alias);
Assert.Equal(aliasName.Name.ToString(), name);
}
internal static void DottedNameVerification(ExpressionSyntax nameTree, string left, string right)
{
// Verification of the change
Assert.IsType<QualifiedNameSyntax>(nameTree);
var dottedName = nameTree as QualifiedNameSyntax;
Assert.Equal(dottedName.Left.ToString(), left);
Assert.Equal(dottedName.Right.ToString(), right);
}
internal static void GenericNameVerification(ExpressionSyntax nameTree, string name, params string[] typeNames)
{
// Verification of the change
Assert.IsType<GenericNameSyntax>(nameTree);
var genericName = nameTree as GenericNameSyntax;
Assert.Equal(genericName.Identifier.ToString(), name);
Assert.Equal(genericName.TypeArgumentList.Arguments.Count, typeNames.Count());
int i = 0;
foreach (string str in typeNames)
{
Assert.Equal(genericName.TypeArgumentList.Arguments[i].ToString(), str);
i++;
}
}
internal static void BasicNameVerification(ExpressionSyntax nameTree, string name)
{
// Verification of the change
Assert.IsType<IdentifierNameSyntax>(nameTree);
var genericName = nameTree as IdentifierNameSyntax;
Assert.Equal(genericName.ToString(), name);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Xunit;
//test
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class NodeValidators
{
#region Verifiers
internal static void PointerNameVerification(ExpressionSyntax nameTree, string name)
{
Assert.IsType<PointerTypeSyntax>(nameTree);
var pointerName = nameTree as PointerTypeSyntax;
Assert.Equal(pointerName.ElementType.ToString(), name);
}
internal static void PredefinedNameVerification(ExpressionSyntax nameTree, string typeName)
{
Assert.IsType<PredefinedTypeSyntax>(nameTree);
var predefName = nameTree as PredefinedTypeSyntax;
Assert.Equal(predefName.ToString(), typeName);
}
internal static void ArrayNameVerification(ExpressionSyntax nameTree, string arrayName, int numRanks)
{
Assert.IsType<ArrayTypeSyntax>(nameTree);
var arrayType = nameTree as ArrayTypeSyntax;
Assert.Equal(arrayType.ElementType.ToString(), arrayName);
Assert.Equal(arrayType.RankSpecifiers.Count(), numRanks);
}
internal static void AliasedNameVerification(ExpressionSyntax nameTree, string alias, string name)
{
// Verification of the change
Assert.IsType<AliasQualifiedNameSyntax>(nameTree);
var aliasName = nameTree as AliasQualifiedNameSyntax;
Assert.Equal(aliasName.Alias.ToString(), alias);
Assert.Equal(aliasName.Name.ToString(), name);
}
internal static void DottedNameVerification(ExpressionSyntax nameTree, string left, string right)
{
// Verification of the change
Assert.IsType<QualifiedNameSyntax>(nameTree);
var dottedName = nameTree as QualifiedNameSyntax;
Assert.Equal(dottedName.Left.ToString(), left);
Assert.Equal(dottedName.Right.ToString(), right);
}
internal static void GenericNameVerification(ExpressionSyntax nameTree, string name, params string[] typeNames)
{
// Verification of the change
Assert.IsType<GenericNameSyntax>(nameTree);
var genericName = nameTree as GenericNameSyntax;
Assert.Equal(genericName.Identifier.ToString(), name);
Assert.Equal(genericName.TypeArgumentList.Arguments.Count, typeNames.Count());
int i = 0;
foreach (string str in typeNames)
{
Assert.Equal(genericName.TypeArgumentList.Arguments[i].ToString(), str);
i++;
}
}
internal static void BasicNameVerification(ExpressionSyntax nameTree, string name)
{
// Verification of the change
Assert.IsType<IdentifierNameSyntax>(nameTree);
var genericName = nameTree as IdentifierNameSyntax;
Assert.Equal(genericName.ToString(), name);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Lsif/Generator/Graph/HoverResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Newtonsoft.Json;
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph
{
/// <summary>
/// Represents a foverResult vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/main/indexFormat/specification.md#more-about-request-textdocumenthover for further details.
/// </summary>
internal sealed class HoverResult : Vertex
{
[JsonProperty("result")]
public Hover Result { get; }
public HoverResult(Hover result, IdFactory idFactory)
: base(label: "hoverResult", idFactory)
{
Result = result;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Newtonsoft.Json;
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph
{
/// <summary>
/// Represents a foverResult vertex for serialization. See https://github.com/Microsoft/language-server-protocol/blob/main/indexFormat/specification.md#more-about-request-textdocumenthover for further details.
/// </summary>
internal sealed class HoverResult : Vertex
{
[JsonProperty("result")]
public Hover Result { get; }
public HoverResult(Hover result, IdFactory idFactory)
: base(label: "hoverResult", idFactory)
{
Result = result;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Emit/ErrorType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using System.Reflection.Metadata;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Error type symbols should be replaced with an object of this class
/// in the translation layer for emit.
/// </summary>
internal class ErrorType : Cci.INamespaceTypeReference
{
public static readonly ErrorType Singleton = new ErrorType();
/// <summary>
/// For the name we will use a word "Error" followed by a guid, generated on the spot.
/// </summary>
private static readonly string s_name = "Error" + Guid.NewGuid().ToString("B");
Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context)
{
return ErrorAssembly.Singleton;
}
string Cci.INamespaceTypeReference.NamespaceName
{
get
{
return "";
}
}
ushort Cci.INamedTypeReference.GenericParameterCount
{
get
{
return 0;
}
}
bool Cci.INamedTypeReference.MangleName
{
get
{
return false;
}
}
bool Cci.ITypeReference.IsEnum
{
get
{
return false;
}
}
bool Cci.ITypeReference.IsValueType
{
get
{
return false;
}
}
Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context)
{
return null;
}
Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode
{
get
{
return Cci.PrimitiveTypeCode.NotPrimitive;
}
}
TypeDefinitionHandle Cci.ITypeReference.TypeDef
{
get
{
return default(TypeDefinitionHandle);
}
}
Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference
{
get
{
return null;
}
}
Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference
{
get
{
return null;
}
}
Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference
{
get
{
return null;
}
}
Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context)
{
return null;
}
Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference
{
get
{
return this;
}
}
Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context)
{
return null;
}
Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference
{
get
{
return null;
}
}
Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference
{
get
{
return null;
}
}
Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context)
{
return null;
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.INamespaceTypeReference)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return null;
}
Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
string Cci.INamedEntity.Name
{
get
{
return s_name;
}
}
public sealed override bool Equals(object obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
/// <summary>
/// A fake containing assembly for an ErrorType object.
/// </summary>
private sealed class ErrorAssembly : Cci.IAssemblyReference
{
public static readonly ErrorAssembly Singleton = new ErrorAssembly();
/// <summary>
/// For the name we will use a word "Error" followed by a guid, generated on the spot.
/// </summary>
private static readonly AssemblyIdentity s_identity = new AssemblyIdentity(
name: "Error" + Guid.NewGuid().ToString("B"),
version: AssemblyIdentity.NullVersion,
cultureName: "",
publicKeyOrToken: ImmutableArray<byte>.Empty,
hasPublicKey: false,
isRetargetable: false,
contentType: AssemblyContentType.Default);
AssemblyIdentity Cci.IAssemblyReference.Identity => s_identity;
Version Cci.IAssemblyReference.AssemblyVersionPattern => null;
Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context)
{
return this;
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IAssemblyReference)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return null;
}
Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
string Cci.INamedEntity.Name => s_identity.Name;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using System.Reflection.Metadata;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Error type symbols should be replaced with an object of this class
/// in the translation layer for emit.
/// </summary>
internal class ErrorType : Cci.INamespaceTypeReference
{
public static readonly ErrorType Singleton = new ErrorType();
/// <summary>
/// For the name we will use a word "Error" followed by a guid, generated on the spot.
/// </summary>
private static readonly string s_name = "Error" + Guid.NewGuid().ToString("B");
Cci.IUnitReference Cci.INamespaceTypeReference.GetUnit(EmitContext context)
{
return ErrorAssembly.Singleton;
}
string Cci.INamespaceTypeReference.NamespaceName
{
get
{
return "";
}
}
ushort Cci.INamedTypeReference.GenericParameterCount
{
get
{
return 0;
}
}
bool Cci.INamedTypeReference.MangleName
{
get
{
return false;
}
}
bool Cci.ITypeReference.IsEnum
{
get
{
return false;
}
}
bool Cci.ITypeReference.IsValueType
{
get
{
return false;
}
}
Cci.ITypeDefinition Cci.ITypeReference.GetResolvedType(EmitContext context)
{
return null;
}
Cci.PrimitiveTypeCode Cci.ITypeReference.TypeCode
{
get
{
return Cci.PrimitiveTypeCode.NotPrimitive;
}
}
TypeDefinitionHandle Cci.ITypeReference.TypeDef
{
get
{
return default(TypeDefinitionHandle);
}
}
Cci.IGenericMethodParameterReference Cci.ITypeReference.AsGenericMethodParameterReference
{
get
{
return null;
}
}
Cci.IGenericTypeInstanceReference Cci.ITypeReference.AsGenericTypeInstanceReference
{
get
{
return null;
}
}
Cci.IGenericTypeParameterReference Cci.ITypeReference.AsGenericTypeParameterReference
{
get
{
return null;
}
}
Cci.INamespaceTypeDefinition Cci.ITypeReference.AsNamespaceTypeDefinition(EmitContext context)
{
return null;
}
Cci.INamespaceTypeReference Cci.ITypeReference.AsNamespaceTypeReference
{
get
{
return this;
}
}
Cci.INestedTypeDefinition Cci.ITypeReference.AsNestedTypeDefinition(EmitContext context)
{
return null;
}
Cci.INestedTypeReference Cci.ITypeReference.AsNestedTypeReference
{
get
{
return null;
}
}
Cci.ISpecializedNestedTypeReference Cci.ITypeReference.AsSpecializedNestedTypeReference
{
get
{
return null;
}
}
Cci.ITypeDefinition Cci.ITypeReference.AsTypeDefinition(EmitContext context)
{
return null;
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.INamespaceTypeReference)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return null;
}
Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
string Cci.INamedEntity.Name
{
get
{
return s_name;
}
}
public sealed override bool Equals(object obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
/// <summary>
/// A fake containing assembly for an ErrorType object.
/// </summary>
private sealed class ErrorAssembly : Cci.IAssemblyReference
{
public static readonly ErrorAssembly Singleton = new ErrorAssembly();
/// <summary>
/// For the name we will use a word "Error" followed by a guid, generated on the spot.
/// </summary>
private static readonly AssemblyIdentity s_identity = new AssemblyIdentity(
name: "Error" + Guid.NewGuid().ToString("B"),
version: AssemblyIdentity.NullVersion,
cultureName: "",
publicKeyOrToken: ImmutableArray<byte>.Empty,
hasPublicKey: false,
isRetargetable: false,
contentType: AssemblyContentType.Default);
AssemblyIdentity Cci.IAssemblyReference.Identity => s_identity;
Version Cci.IAssemblyReference.AssemblyVersionPattern => null;
Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context)
{
return this;
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IAssemblyReference)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return null;
}
Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
string Cci.INamedEntity.Name => s_identity.Name;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Shared/TestHooks/Legacy/ListenerForwarders.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.CompilerServices;
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListener))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListenerProvider))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.EmptyAsyncToken))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListenerProvider))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationWaiter))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListener))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsyncToken))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.TaskExtensions))]
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Runtime.CompilerServices;
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListener))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListenerProvider))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.EmptyAsyncToken))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListenerProvider))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationWaiter))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListener))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsyncToken))]
[assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.TaskExtensions))]
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/ImportRecord.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal readonly struct ImportRecord
{
public readonly ImportTargetKind TargetKind;
public readonly string? Alias;
// target type of a type import (C#)
public readonly ITypeSymbolInternal? TargetType;
// target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB)
public readonly string? TargetString;
// target assembly of a namespace import (C#, Portable)
public readonly IAssemblySymbolInternal? TargetAssembly;
// target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB)
public readonly string? TargetAssemblyAlias;
public ImportRecord(
ImportTargetKind targetKind,
string? alias = null,
ITypeSymbolInternal? targetType = null,
string? targetString = null,
IAssemblySymbolInternal? targetAssembly = null,
string? targetAssemblyAlias = null)
{
TargetKind = targetKind;
Alias = alias;
TargetType = targetType;
TargetString = targetString;
TargetAssembly = targetAssembly;
TargetAssemblyAlias = targetAssemblyAlias;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal readonly struct ImportRecord
{
public readonly ImportTargetKind TargetKind;
public readonly string? Alias;
// target type of a type import (C#)
public readonly ITypeSymbolInternal? TargetType;
// target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB)
public readonly string? TargetString;
// target assembly of a namespace import (C#, Portable)
public readonly IAssemblySymbolInternal? TargetAssembly;
// target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB)
public readonly string? TargetAssemblyAlias;
public ImportRecord(
ImportTargetKind targetKind,
string? alias = null,
ITypeSymbolInternal? targetType = null,
string? targetString = null,
IAssemblySymbolInternal? targetAssembly = null,
string? targetAssemblyAlias = null)
{
TargetKind = targetKind;
Alias = alias;
TargetType = targetType;
TargetString = targetString;
TargetAssembly = targetAssembly;
TargetAssemblyAlias = targetAssemblyAlias;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Server/VBCSCompiler/ClientConnectionHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.CompilerServer
{
/// <summary>
/// This class is responsible for processing a request from a client of the compiler server.
/// </summary>
internal sealed class ClientConnectionHandler
{
internal ICompilerServerHost CompilerServerHost { get; }
internal ICompilerServerLogger Logger => CompilerServerHost.Logger;
internal ClientConnectionHandler(ICompilerServerHost compilerServerHost)
{
CompilerServerHost = compilerServerHost;
}
/// <summary>
/// Handles a client connection. The returned task here will never fail. Instead all exceptions will be wrapped
/// in a <see cref="CompletionReason.RequestError"/>
/// </summary>
internal async Task<CompletionData> ProcessAsync(
Task<IClientConnection> clientConnectionTask,
bool allowCompilationRequests = true,
CancellationToken cancellationToken = default)
{
try
{
return await ProcessCore().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogException(ex, $"Error processing request for client");
return CompletionData.RequestError;
}
async Task<CompletionData> ProcessCore()
{
using var clientConnection = await clientConnectionTask.ConfigureAwait(false);
var request = await clientConnection.ReadBuildRequestAsync(cancellationToken).ConfigureAwait(false);
Logger.Log($"Received request {request.RequestId} of type {request.GetType()}");
if (!string.Equals(request.CompilerHash, BuildProtocolConstants.GetCommitHash(), StringComparison.OrdinalIgnoreCase))
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new IncorrectHashBuildResponse(),
CompletionData.RequestError,
cancellationToken).ConfigureAwait(false);
}
if (request.Arguments.Count == 1 && request.Arguments[0].ArgumentId == BuildProtocolConstants.ArgumentId.Shutdown)
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new ShutdownBuildResponse(Process.GetCurrentProcess().Id),
new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true),
cancellationToken).ConfigureAwait(false);
}
if (!allowCompilationRequests)
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new RejectedBuildResponse("Compilation not allowed at this time"),
CompletionData.RequestCompleted,
cancellationToken).ConfigureAwait(false);
}
if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable(Logger))
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new RejectedBuildResponse("Not enough resources to accept connection"),
CompletionData.RequestError,
cancellationToken).ConfigureAwait(false);
}
return await ProcessCompilationRequestAsync(clientConnection, request, cancellationToken).ConfigureAwait(false);
}
}
private async Task<CompletionData> WriteBuildResponseAsync(IClientConnection clientConnection, Guid requestId, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken)
{
var message = response switch
{
RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {requestId}",
_ => $"Writing {response.Type} response for {requestId}"
};
Logger.Log(message);
await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false);
return completionData;
}
private async Task<CompletionData> ProcessCompilationRequestAsync(IClientConnection clientConnection, BuildRequest request, CancellationToken cancellationToken)
{
// Need to wait for the compilation and client disconnection in parallel. If the client
// suddenly disconnects we need to cancel the compilation that is occurring. It could be the
// client hit Ctrl-C due to a run away analyzer.
var buildCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var compilationTask = ProcessCompilationRequestCore(CompilerServerHost, request, buildCancellationTokenSource.Token);
await Task.WhenAny(compilationTask, clientConnection.DisconnectTask).ConfigureAwait(false);
try
{
if (compilationTask.IsCompleted)
{
BuildResponse response;
CompletionData completionData;
try
{
response = await compilationTask.ConfigureAwait(false);
completionData = response switch
{
// Once there is an analyzer inconsistency the assembly load space is polluted. The
// request is an error.
AnalyzerInconsistencyBuildResponse _ => CompletionData.RequestError,
_ => new CompletionData(CompletionReason.RequestCompleted, newKeepAlive: CheckForNewKeepAlive(request))
};
}
catch (Exception ex)
{
// The compilation task should never throw. If it does we need to assume that the compiler is
// in a bad state and need to issue a RequestError
Logger.LogException(ex, $"Exception running compilation for {request.RequestId}");
response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}");
completionData = CompletionData.RequestError;
}
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
response,
completionData,
cancellationToken).ConfigureAwait(false);
}
else
{
return CompletionData.RequestError;
}
}
finally
{
buildCancellationTokenSource.Cancel();
}
static Task<BuildResponse> ProcessCompilationRequestCore(ICompilerServerHost compilerServerHost, BuildRequest buildRequest, CancellationToken cancellationToken)
{
Func<BuildResponse> func = () =>
{
var request = BuildProtocolUtil.GetRunRequest(buildRequest);
var response = compilerServerHost.RunCompilation(request, cancellationToken);
return response;
};
var task = new Task<BuildResponse>(func, cancellationToken, TaskCreationOptions.LongRunning);
task.Start();
return task;
}
}
/// <summary>
/// Check the request arguments for a new keep alive time. If one is present,
/// set the server timer to the new time.
/// </summary>
private static TimeSpan? CheckForNewKeepAlive(BuildRequest request)
{
TimeSpan? timeout = null;
foreach (var arg in request.Arguments)
{
if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.KeepAlive)
{
int result;
// If the value is not a valid integer for any reason,
// ignore it and continue with the current timeout. The client
// is responsible for validating the argument.
if (int.TryParse(arg.Value, out result))
{
// Keep alive times are specified in seconds
timeout = TimeSpan.FromSeconds(result);
}
}
}
return timeout;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.CompilerServer
{
/// <summary>
/// This class is responsible for processing a request from a client of the compiler server.
/// </summary>
internal sealed class ClientConnectionHandler
{
internal ICompilerServerHost CompilerServerHost { get; }
internal ICompilerServerLogger Logger => CompilerServerHost.Logger;
internal ClientConnectionHandler(ICompilerServerHost compilerServerHost)
{
CompilerServerHost = compilerServerHost;
}
/// <summary>
/// Handles a client connection. The returned task here will never fail. Instead all exceptions will be wrapped
/// in a <see cref="CompletionReason.RequestError"/>
/// </summary>
internal async Task<CompletionData> ProcessAsync(
Task<IClientConnection> clientConnectionTask,
bool allowCompilationRequests = true,
CancellationToken cancellationToken = default)
{
try
{
return await ProcessCore().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogException(ex, $"Error processing request for client");
return CompletionData.RequestError;
}
async Task<CompletionData> ProcessCore()
{
using var clientConnection = await clientConnectionTask.ConfigureAwait(false);
var request = await clientConnection.ReadBuildRequestAsync(cancellationToken).ConfigureAwait(false);
Logger.Log($"Received request {request.RequestId} of type {request.GetType()}");
if (!string.Equals(request.CompilerHash, BuildProtocolConstants.GetCommitHash(), StringComparison.OrdinalIgnoreCase))
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new IncorrectHashBuildResponse(),
CompletionData.RequestError,
cancellationToken).ConfigureAwait(false);
}
if (request.Arguments.Count == 1 && request.Arguments[0].ArgumentId == BuildProtocolConstants.ArgumentId.Shutdown)
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new ShutdownBuildResponse(Process.GetCurrentProcess().Id),
new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true),
cancellationToken).ConfigureAwait(false);
}
if (!allowCompilationRequests)
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new RejectedBuildResponse("Compilation not allowed at this time"),
CompletionData.RequestCompleted,
cancellationToken).ConfigureAwait(false);
}
if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable(Logger))
{
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
new RejectedBuildResponse("Not enough resources to accept connection"),
CompletionData.RequestError,
cancellationToken).ConfigureAwait(false);
}
return await ProcessCompilationRequestAsync(clientConnection, request, cancellationToken).ConfigureAwait(false);
}
}
private async Task<CompletionData> WriteBuildResponseAsync(IClientConnection clientConnection, Guid requestId, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken)
{
var message = response switch
{
RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {requestId}",
_ => $"Writing {response.Type} response for {requestId}"
};
Logger.Log(message);
await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false);
return completionData;
}
private async Task<CompletionData> ProcessCompilationRequestAsync(IClientConnection clientConnection, BuildRequest request, CancellationToken cancellationToken)
{
// Need to wait for the compilation and client disconnection in parallel. If the client
// suddenly disconnects we need to cancel the compilation that is occurring. It could be the
// client hit Ctrl-C due to a run away analyzer.
var buildCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var compilationTask = ProcessCompilationRequestCore(CompilerServerHost, request, buildCancellationTokenSource.Token);
await Task.WhenAny(compilationTask, clientConnection.DisconnectTask).ConfigureAwait(false);
try
{
if (compilationTask.IsCompleted)
{
BuildResponse response;
CompletionData completionData;
try
{
response = await compilationTask.ConfigureAwait(false);
completionData = response switch
{
// Once there is an analyzer inconsistency the assembly load space is polluted. The
// request is an error.
AnalyzerInconsistencyBuildResponse _ => CompletionData.RequestError,
_ => new CompletionData(CompletionReason.RequestCompleted, newKeepAlive: CheckForNewKeepAlive(request))
};
}
catch (Exception ex)
{
// The compilation task should never throw. If it does we need to assume that the compiler is
// in a bad state and need to issue a RequestError
Logger.LogException(ex, $"Exception running compilation for {request.RequestId}");
response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}");
completionData = CompletionData.RequestError;
}
return await WriteBuildResponseAsync(
clientConnection,
request.RequestId,
response,
completionData,
cancellationToken).ConfigureAwait(false);
}
else
{
return CompletionData.RequestError;
}
}
finally
{
buildCancellationTokenSource.Cancel();
}
static Task<BuildResponse> ProcessCompilationRequestCore(ICompilerServerHost compilerServerHost, BuildRequest buildRequest, CancellationToken cancellationToken)
{
Func<BuildResponse> func = () =>
{
var request = BuildProtocolUtil.GetRunRequest(buildRequest);
var response = compilerServerHost.RunCompilation(request, cancellationToken);
return response;
};
var task = new Task<BuildResponse>(func, cancellationToken, TaskCreationOptions.LongRunning);
task.Start();
return task;
}
}
/// <summary>
/// Check the request arguments for a new keep alive time. If one is present,
/// set the server timer to the new time.
/// </summary>
private static TimeSpan? CheckForNewKeepAlive(BuildRequest request)
{
TimeSpan? timeout = null;
foreach (var arg in request.Arguments)
{
if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.KeepAlive)
{
int result;
// If the value is not a valid integer for any reason,
// ignore it and continue with the current timeout. The client
// is responsible for validating the argument.
if (int.TryParse(arg.Value, out result))
{
// Keep alive times are specified in seconds
timeout = TimeSpan.FromSeconds(result);
}
}
}
return timeout;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Emit/PDB/PDBUsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.Metadata.Tools;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBUsingTests : CSharpPDBTestBase
{
#region Helpers
private static CSharpCompilation CreateDummyCompilation(string assemblyName)
{
return CreateCompilation(
"public class C { }",
assemblyName: assemblyName,
options: TestOptions.DebugDll);
}
#endregion
[Fact]
public void TestUsings()
{
var text = @"
using System;
class A { void M() { } }
namespace X
{
using System.IO;
class B { void M() { } }
namespace Y
{
using System.Threading;
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System.IO"" />
<namespace name=""System"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System.Threading"" />
<namespace name=""System.IO"" />
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestNamespaceAliases()
{
var text = @"
using P = System;
class A { void M() { } }
namespace X
{
using Q = System.IO;
class B { void M() { } }
namespace Y
{
using R = System.Threading;
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""Q"" target=""System.IO"" kind=""namespace"" />
<alias name=""P"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""R"" target=""System.Threading"" kind=""namespace"" />
<alias name=""Q"" target=""System.IO"" kind=""namespace"" />
<alias name=""P"" target=""System"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestTypeAliases1()
{
var text = @"
using P = System.String;
class A { void M() { } }
namespace X
{
using Q = System.Int32;
class B { void M() { } }
namespace Y
{
using R = System.Char;
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""Q"" target=""System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""R"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""Q"" target=""System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestTypeAliases2()
{
var text = @"
using P = System.Collections.Generic.List<int>;
class A { void M() { } }
namespace X
{
using Q = System.Collections.Generic.List<System.Collections.Generic.List<char>>;
class B { void M() { } }
namespace Y
{
using P = System.Char; //hides previous P
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""Q"" target=""System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""Q"" target=""System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestExternAliases1()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
var text = @"
extern alias P;
class A { void M() { } }
namespace X
{
extern alias Q;
class B { void M() { } }
namespace Y
{
extern alias R;
class C { void M() { } }
}
}
";
var compilation = CreateCompilation(text,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")) ,
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R"))
});
compilation.VerifyDiagnostics(
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (8,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"),
// (14,9): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""P"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<extern alias=""P"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<extern alias=""Q"" />
<extern alias=""P"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(1120579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120579")]
public void TestExternAliases2()
{
string source1 = @"
namespace U.V.W {}
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, assemblyName: "TestExternAliases2");
string source2 = @"
using U.V.W;
class A { void M() { } }
";
var compilation2 = CreateCompilation(
source2,
options: TestOptions.DebugDll,
references: new[]
{
// first unaliased reference
compilation1.ToMetadataReference(),
// second aliased reference
compilation1.ToMetadataReference(ImmutableArray.Create("X"))
});
compilation2.VerifyPdb("A.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""23"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""U.V.W"" />
<externinfo alias=""X"" assembly=""TestExternAliases2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(1120579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120579")]
public void TestExternAliases3()
{
string source1 = @"
namespace U.V.W {}
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, assemblyName: "TestExternAliases3");
string source2 = @"
using U.V.W;
class A { void M() { } }
";
var compilation2 = CreateCompilation(
source2,
options: TestOptions.DebugDll,
references: new[]
{
// first aliased reference
compilation1.ToMetadataReference(ImmutableArray.Create("X")),
// second unaliased reference
compilation1.ToMetadataReference(),
});
compilation2.VerifyPdb("A.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""23"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""U.V.W"" />
<externinfo alias=""X"" assembly=""TestExternAliases3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ExternAliases4()
{
var src1 = @"
namespace N
{
public class C { }
}";
var dummyCompilation = CreateCompilation(src1, assemblyName: "A", options: TestOptions.DebugDll);
var src2 = @"
namespace M
{
extern alias A;
using A::N;
public class D
{
public C P
{
get { return new C(); }
set { }
}
}
}";
var compilation = CreateCompilation(src2,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation, ImmutableArray.Create("A", "A")),
});
compilation.VerifyDiagnostics();
compilation.VerifyEmitDiagnostics();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestExternAliases_ExplicitAndGlobal()
{
var dummySource = @"
namespace N
{
public class C { }
}
";
CSharpCompilation dummyCompilation1 = CreateCompilation(dummySource, assemblyName: "A", options: TestOptions.DebugDll);
CSharpCompilation dummyCompilation2 = CreateCompilation(dummySource, assemblyName: "B", options: TestOptions.DebugDll);
var text = @"
extern alias A;
extern alias B;
using X = A::N;
using Y = B::N;
using Z = global::N;
class C { void M() { } }
";
var compilation = CreateCompilation(text,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("global", "A")),
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("B", "global"))
});
compilation.VerifyDiagnostics(
// (5,1): hidden CS8019: Unnecessary using directive.
// using Y = B::N;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Y = B::N;").WithLocation(5, 1),
// (4,1): hidden CS8019: Unnecessary using directive.
// using X = A::N;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = A::N;").WithLocation(4, 1),
// (6,1): hidden CS8019: Unnecessary using directive.
// using Z = global::N;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Z = global::N;").WithLocation(6, 1));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""5""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""20"" endLine=""8"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""A""/>
<extern alias=""B""/>
<alias name=""X"" target=""N"" kind=""namespace""/>
<alias name=""Y"" target=""N"" kind=""namespace""/>
<alias name=""Z"" target=""N"" kind=""namespace""/>
<externinfo alias=""A"" assembly=""A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""/>
<externinfo alias=""B"" assembly=""B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""/>
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestExternAliasesInUsing()
{
CSharpCompilation libComp = CreateCompilation(@"
namespace N
{
public class A { }
}", assemblyName: "Lib");
var text = @"
extern alias P;
using P::N;
using Q = P::N.A;
using R = P::N;
using global::N;
using S = global::N.B;
using T = global::N;
namespace N
{
class B { void M() { } }
}
";
var compilation = CreateCompilation(text,
assemblyName: "Test",
options: TestOptions.DebugDll,
references: new[] { new CSharpCompilationReference(libComp, ImmutableArray.Create("P")) });
compilation.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""N.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""7"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""26"" endLine=""12"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""P"" />
<namespace qualifier=""P"" name=""N"" />
<namespace name=""N"" />
<alias name=""Q"" target=""N.A, Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""R"" qualifier=""P"" target=""N"" kind=""namespace"" />
<alias name=""S"" target=""N.B"" kind=""type"" />
<alias name=""T"" target=""N"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestNamespacesAndAliases()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
var text = @"
extern alias P;
using System;
using AU1 = System;
using AT1 = System.Char;
class A { void M() { } }
namespace X
{
extern alias Q;
using AU2 = System.IO;
using AT2 = System.IO.Directory;
using System.IO;
class B { void M() { } }
namespace Y
{
extern alias R;
using AT3 = System.Text.StringBuilder;
using System.Text;
using AU3 = System.Text;
class C { void M() { } }
}
}
";
var compilation = CreateCompilation(text,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")) ,
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R"))
});
compilation.VerifyDiagnostics(
// (3,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU1 = System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU1 = System;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT1 = System.Char;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT1 = System.Char;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (12,5): info CS8019: Unnecessary using directive.
// using AU2 = System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU2 = System.IO;"),
// (13,5): info CS8019: Unnecessary using directive.
// using AT2 = System.IO.Directory;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT2 = System.IO.Directory;"),
// (14,5): info CS8019: Unnecessary using directive.
// using System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.IO;"),
// (11,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"),
// (21,9): info CS8019: Unnecessary using directive.
// using AT3 = System.Text.StringBuilder;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT3 = System.Text.StringBuilder;"),
// (22,9): info CS8019: Unnecessary using directive.
// using System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Text;"),
// (23,9): info CS8019: Unnecessary using directive.
// using AU3 = System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU3 = System.Text;"),
// (20,9): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""24"" endLine=""16"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""26"" endLine=""16"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""25"" startColumn=""28"" endLine=""25"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""25"" startColumn=""30"" endLine=""25"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<namespace name=""System.Text"" />
<alias name=""AT3"" target=""System.Text.StringBuilder, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Text"" kind=""namespace"" />
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737"), WorkItem(913022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913022")]
public void ReferenceWithMultipleAliases()
{
var source1 = @"
namespace N { public class D { } }
namespace M { public class E { } }
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var source2 = @"
extern alias A;
extern alias B;
using A::N;
using B::M;
using X = A::N;
using Y = B::N;
public class C
{
public static void Main()
{
System.Console.WriteLine(new D());
System.Console.WriteLine(new E());
System.Console.WriteLine(new X.D());
System.Console.WriteLine(new Y.D());
}
}";
var compilation2 = CreateCompilation(source2,
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(compilation1, ImmutableArray.Create("A", "B"))
});
compilation2.VerifyDiagnostics();
compilation2.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""6""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""43"" document=""1"" />
<entry offset=""0xc"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""43"" document=""1"" />
<entry offset=""0x17"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""45"" document=""1"" />
<entry offset=""0x22"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""45"" document=""1"" />
<entry offset=""0x2d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<extern alias=""A""/>
<extern alias=""B""/>
<namespace qualifier=""A"" name=""N""/>
<namespace qualifier=""A"" name=""M""/>
<alias name=""X"" qualifier=""A"" target=""N"" kind=""namespace""/>
<alias name=""Y"" qualifier=""A"" target=""N"" kind=""namespace""/>
<externinfo alias = ""A"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias = ""B"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(913022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913022")]
public void ReferenceWithGlobalAndDuplicateAliases()
{
var source1 = @"
namespace N { public class D { } }
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var source2 = @"
extern alias A;
extern alias B;
public class C
{
public static void Main()
{
System.Console.WriteLine(new N.D());
System.Console.WriteLine(new A::N.D());
System.Console.WriteLine(new B::N.D());
}
}";
var compilation2 = CreateCompilation(source2,
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(compilation1, ImmutableArray.Create("global", "B", "A", "A", "global"))
});
compilation2.VerifyDiagnostics();
compilation2.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""45"" document=""1"" />
<entry offset=""0xc"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""48"" document=""1"" />
<entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""48"" document=""1"" />
<entry offset=""0x22"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x23"">
<extern alias=""A"" />
<extern alias=""B"" />
<externinfo alias=""B"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""A"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestPartialTypeInOneFile()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
var text1 = @"
extern alias P;
using System;
using AU1 = System;
using AT1 = System.Char;
namespace X
{
extern alias Q;
using AU2 = System.IO;
using AT2 = System.IO.Directory;
using System.IO;
partial class C
{
partial void M();
void N1() { }
}
}
namespace X
{
extern alias R;
using AU3 = System.Threading;
using AT3 = System.Threading.Thread;
using System.Threading;
partial class C
{
partial void M() { }
void N2() { }
}
}
";
var compilation = CreateCompilation(
text1,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")),
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R")),
});
compilation.VerifyDiagnostics(
// (3,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU1 = System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU1 = System;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT1 = System.Char;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT1 = System.Char;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (24,5): info CS8019: Unnecessary using directive.
// using AU3 = System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU3 = System.Threading;"),
// (25,5): info CS8019: Unnecessary using directive.
// using AT3 = System.Threading.Thread;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT3 = System.Threading.Thread;"),
// (26,5): info CS8019: Unnecessary using directive.
// using System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading;"),
// (23,5): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"),
// (10,5): info CS8019: Unnecessary using directive.
// using AU2 = System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU2 = System.IO;"),
// (11,5): info CS8019: Unnecessary using directive.
// using AT2 = System.IO.Directory;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT2 = System.IO.Directory;"),
// (12,5): info CS8019: Unnecessary using directive.
// using System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.IO;"),
// (9,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""X.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""27"" document=""1"" />
<entry offset=""0x1"" startLine=""30"" startColumn=""28"" endLine=""30"" endColumn=""29"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<namespace name=""System.Threading"" />
<alias name=""AT3"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.C"" name=""N1"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.C"" name=""N2"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""31"" startColumn=""19"" endLine=""31"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""31"" startColumn=""21"" endLine=""31"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<namespace name=""System.Threading"" />
<alias name=""AT3"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>", options: PdbValidationOptions.SkipConversionValidation); // TODO: https://github.com/dotnet/roslyn/issues/18004
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestPartialTypeInTwoFiles()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
CSharpCompilation dummyCompilation4 = CreateDummyCompilation("d");
var text1 = @"
extern alias P;
using System;
using AU1 = System;
using AT1 = System.Char;
namespace X
{
extern alias Q;
using AU2 = System.IO;
using AT2 = System.IO.Directory;
using System.IO;
partial class C
{
partial void M();
void N1() { }
}
}
";
var text2 = @"
extern alias R;
using System.Text;
using AU3 = System.Text;
using AT3 = System.Text.StringBuilder;
namespace X
{
extern alias S;
using AU4 = System.Threading;
using AT4 = System.Threading.Thread;
using System.Threading;
partial class C
{
partial void M() { }
void N2() { }
}
}
";
var compilation = CreateCompilation(
new string[] { text1, text2 },
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")),
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R")),
new CSharpCompilationReference(dummyCompilation4, ImmutableArray.Create("S")),
});
compilation.VerifyDiagnostics(
// (3,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU1 = System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU1 = System;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT1 = System.Char;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT1 = System.Char;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Text;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU3 = System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU3 = System.Text;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT3 = System.Text.StringBuilder;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT3 = System.Text.StringBuilder;"),
// (10,5): info CS8019: Unnecessary using directive.
// using AU2 = System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU2 = System.IO;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"),
// (11,5): info CS8019: Unnecessary using directive.
// using AT2 = System.IO.Directory;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT2 = System.IO.Directory;"),
// (12,5): info CS8019: Unnecessary using directive.
// using System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.IO;"),
// (10,5): info CS8019: Unnecessary using directive.
// using AU4 = System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU4 = System.Threading;"),
// (9,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"),
// (11,5): info CS8019: Unnecessary using directive.
// using AT4 = System.Threading.Thread;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT4 = System.Threading.Thread;"),
// (12,5): info CS8019: Unnecessary using directive.
// using System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading;"),
// (9,5): info CS8020: Unused extern alias.
// extern alias S;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias S;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""X.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""26"" endLine=""16"" endColumn=""27"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""S"" />
<namespace name=""System.Threading"" />
<alias name=""AT4"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU4"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""R"" />
<namespace name=""System.Text"" />
<alias name=""AT3"" target=""System.Text.StringBuilder, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Text"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""S"" assembly=""d, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.C"" name=""N1"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.C"" name=""N2"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""S"" />
<namespace name=""System.Threading"" />
<alias name=""AT4"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU4"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""R"" />
<namespace name=""System.Text"" />
<alias name=""AT3"" target=""System.Text.StringBuilder, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Text"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>", options: PdbValidationOptions.SkipConversionValidation); // TODO: https://github.com/dotnet/roslyn/issues/18004
}
[Fact]
public void TestSynthesizedConstructors()
{
var text = @"
namespace X
{
using System;
partial class C
{
int x = 1;
static int sx = 1;
}
}
namespace X
{
using System.IO;
partial class C
{
int y = 1;
static int sy = 1;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""X.C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1""/>
<namespace usingCount=""0""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0x7"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""19"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<namespace name=""System""/>
</scope>
</method>
<method containingType=""X.C"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""X.C"" methodName="".ctor""/>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" />
<entry offset=""0x6"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""27"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestFieldInitializerLambdas()
{
var text = WithWindowsLineBreaks(@"
using System.Linq;
class C
{
int x = new int[2].Count(x => { return x % 3 == 0; });
static bool sx = new int[2].Any(x =>
{
return x % 2 == 0;
});
}
");
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<lambda offset=""-23"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""59"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
</scope>
</method>
<method containingType=""C"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLambdaMap>
<methodOrdinal>3</methodOrdinal>
<lambda offset=""-38"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""10"" endColumn=""8"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__2_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""-23"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""35"" endLine=""6"" endColumn=""36"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""37"" endLine=""6"" endColumn=""55"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""56"" endLine=""6"" endColumn=""57"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__3_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""-38"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" />
<entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestAccessors()
{
var text = WithWindowsLineBreaks(@"
using System;
class C
{
int P1 { get; set; }
int P2 { get { return 0; } set { } }
int this[int x] { get { return 0; } set { } }
event System.Action E1;
event System.Action E2 { add { } remove { } }
}
");
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P1"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""14"" endLine=""6"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_P1"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""19"" endLine=""6"" endColumn=""23"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_P2"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""29"" document=""1"" />
<entry offset=""0x5"" startLine=""7"" startColumn=""30"" endLine=""7"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""set_P2"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""36"" endLine=""7"" endColumn=""37"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""38"" endLine=""7"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_Item"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""28"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""29"" endLine=""8"" endColumn=""38"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""39"" endLine=""8"" endColumn=""40"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_Item"" parameterNames=""x, value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""8"" endColumn=""46"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""47"" endLine=""8"" endColumn=""48"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""add_E2"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""34"" endLine=""10"" endColumn=""35"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""36"" endLine=""10"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""remove_E2"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""46"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""47"" endLine=""10"" endColumn=""48"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSynthesizedSealedAccessors()
{
var text = @"
using System;
class Base
{
public virtual int P { get; set; }
}
class Derived : Base
{
public sealed override int P { set { } } //have to synthesize a sealed getter
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Base"" name=""get_P"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""28"" endLine=""6"" endColumn=""32"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Base"" name=""set_P"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Derived"" name=""set_P"" parameterNames=""value"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""40"" endLine=""11"" endColumn=""41"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""42"" endLine=""11"" endColumn=""43"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSynthesizedExplicitImplementation()
{
var text = WithWindowsLineBreaks(@"
using System.Runtime.CompilerServices;
interface I1
{
[IndexerName(""A"")]
int this[int x] { get; set; }
}
interface I2
{
[IndexerName(""B"")]
int this[int x] { get; set; }
}
class C : I1, I2
{
public int this[int x] { get { return 0; } set { } }
}
");
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_Item"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""34"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""36"" endLine=""18"" endColumn=""45"" document=""1"" />
<entry offset=""0x5"" startLine=""18"" startColumn=""46"" endLine=""18"" endColumn=""47"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System.Runtime.CompilerServices"" />
</scope>
</method>
<method containingType=""C"" name=""set_Item"" parameterNames=""x, value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_Item"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""52"" endLine=""18"" endColumn=""53"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""54"" endLine=""18"" endColumn=""55"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(692496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/692496")]
[Fact]
public void SequencePointOnUsingExpression()
{
var source = @"
using System;
public class Test : IDisposable
{
static void Main()
{
using (new Test())
{
}
}
public void Dispose() { }
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Test.Main", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (Test V_0)
-IL_0000: nop
-IL_0001: newobj ""Test..ctor()""
IL_0006: stloc.0
.try
{
-IL_0007: nop
-IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
~IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
~IL_0015: endfinally
}
-IL_0016: ret
}", sequencePoints: "Test.Main");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestNestedType()
{
var libSource = @"
public class Outer
{
public class Inner
{
}
}
";
var libRef = CreateCompilation(libSource, assemblyName: "Lib").EmitToImageReference();
var source = @"
using I = Outer.Inner;
public class Test
{
static void Main()
{
}
}
";
CompileAndVerify(source, new[] { libRef }, options: TestOptions.DebugExe).VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""Test"" methodName=""Main"" />
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""I"" target=""Outer+Inner, Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestVerbatimIdentifiers()
{
var source = @"
using @namespace;
using @object = @namespace;
using @string = @namespace.@class<@namespace.@interface>.@struct;
namespace @namespace
{
public class @class<T>
{
public struct @struct
{
}
}
public interface @interface
{
}
}
class Test { static void Main() { } }
";
var comp = CreateCompilation(source);
// As in dev12, we drop all '@'s.
comp.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""20"" startColumn=""35"" endLine=""20"" endColumn=""36"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1"">
<namespace name=""namespace"" />
<alias name=""object"" target=""namespace"" kind=""namespace"" />
<alias name=""string"" target=""namespace.class`1+struct[namespace.interface]"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(842479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842479")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void UsingExternAlias()
{
var libSource = "public class C { }";
var lib = CreateCompilation(libSource, assemblyName: "Lib");
var libRef = lib.EmitToImageReference(aliases: ImmutableArray.Create("Q"));
var source = @"
extern alias Q;
using R = Q;
using Q;
namespace N
{
using S = R;
using R;
class D
{
static void Main() { }
}
}
";
var comp = CreateCompilation(source, new[] { libRef });
comp.VerifyPdb("N.D.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""N.D"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""30"" endLine=""13"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1"">
<namespace qualifier=""Q"" name="""" />
<alias name=""S"" qualifier=""Q"" target="""" kind=""namespace"" />
<extern alias=""Q"" />
<namespace qualifier=""Q"" name="""" />
<alias name=""R"" qualifier=""Q"" target="""" kind=""namespace"" />
<externinfo alias=""Q"" assembly=""Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(842478, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842478")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void AliasIncludingDynamic()
{
var source = @"
using AD = System.Action<dynamic>;
class D
{
static void Main() { }
}
";
var comp = CreateCompilation(source);
comp.VerifyPdb("D.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""D"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""26"" endLine=""6"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1"">
<alias name=""AD"" target=""System.Action`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UsingExpression()
{
TestSequencePoints(
@"using System;
public class Test : IDisposable
{
static void Main()
{
[|using (new Test())|]
{
}
}
public void Dispose() { }
}", TestOptions.ReleaseExe, methodName: "Test.Main");
}
[Fact]
public void UsingVariable()
{
TestSequencePoints(
@"using System;
public class Test : IDisposable
{
static void Main()
{
var x = new Test();
[|using (x)|]
{
}
}
public void Dispose() { }
}", TestOptions.ReleaseExe, methodName: "Test.Main");
}
[WorkItem(546754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546754")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void ArrayType()
{
var source1 = @"
using System;
public class W {}
public class Y<T>
{
public class F {}
public class Z<U> {}
}
";
var comp1 = CreateCompilation(source1, options: TestOptions.DebugDll, assemblyName: "Comp1");
var source2 = @"
using t1 = Y<W[]>;
using t2 = Y<W[,]>;
using t3 = Y<W[,][]>;
using t4 = Y<Y<W>[][,]>;
using t5 = Y<W[,][]>.Z<W[][,,]>;
using t6 = Y<Y<Y<int[]>.F[,][]>.Z<Y<W[,][]>.F[]>[][]>;
public class C1
{
public static void Main()
{
}
}
";
var comp2 = CreateCompilation(source2, new[] { comp1.ToMetadataReference() }, options: TestOptions.DebugExe);
comp2.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C1"" methodName=""Main"" />
<methods>
<method containingType=""C1"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""6"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""t1"" target=""Y`1[[W[], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t2"" target=""Y`1[[W[,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t3"" target=""Y`1[[W[][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t4"" target=""Y`1[[Y`1[[W, Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]][,][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t5"" target=""Y`1+Z`1[[W[][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[W[,,][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t6"" target=""Y`1[[Y`1+Z`1[[Y`1+F[[System.Int32[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[Y`1+F[[W[][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]][][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737"), WorkItem(543615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615")]
public void WRN_DebugFullNameTooLong()
{
var text = @"
using System;
using DICT1 = System.Collections.Generic.Dictionary<int, int>;
namespace goo
{
using ACT = System.Action<DICT1, DICT1, DICT1, DICT1, DICT1, DICT1, DICT1>;
class C
{
static void Main()
{
ACT ac = null;
Console.Write(ac);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.DebugExe);
var exebits = new MemoryStream();
var pdbbits = new MemoryStream();
var result = compilation.Emit(exebits, pdbbits);
result.Diagnostics.Verify(
Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, "Main").WithArguments("AACT TSystem.Action`7[[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
}
[WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")]
[Fact]
public void StaticType()
{
var source = @"
using static System.Math;
class D
{
static void Main()
{
Max(1, 2);
}
}
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40);
comp.VerifyPdb("D.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""D"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0x8"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<type name=""System.Math, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""/>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UnusedImports()
{
var source = @"
extern alias A;
using System;
using X = A::System.Linq.Enumerable;
using Y = A::System.Linq;
using Z = System.Data.DataColumn;
using F = System.Func<int>;
class C
{
static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemCoreRef.WithAliases(new[] { "A" }), SystemDataRef });
var v = CompileAndVerify(comp, validator: (peAssembly) =>
{
var reader = peAssembly.ManifestModule.MetadataReader;
Assert.Equal(new[]
{
"mscorlib",
"System.Core",
"System.Data"
}, peAssembly.AssemblyReferences.Select(ai => ai.Name));
Assert.Equal(new[]
{
"CompilationRelaxationsAttribute",
"RuntimeCompatibilityAttribute",
"DebuggableAttribute",
"DebuggingModes",
"Object",
"Func`1",
"Enumerable",
"DataColumn"
}, reader.TypeReferences.Select(h => reader.GetString(reader.GetTypeReference(h).Name)));
Assert.Equal(1, reader.GetTableRowCount(TableIndex.TypeSpec));
});
}
[Fact]
public void UnusedImports_Nonexisting()
{
var source = @"
extern alias A;
using B;
using X = C.D;
using Y = A::E;
using Z = F<int>;
class C
{
static void Main()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,11): error CS0246: The type or namespace name 'F<>' could not be found (are you missing a using directive or an assembly reference?)
// using Z = F<int>;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "F<int>").WithArguments("F<>").WithLocation(6, 11),
// (5,14): error CS0234: The type or namespace name 'E' does not exist in the namespace 'A' (are you missing an assembly reference?)
// using Y = A::E;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "E").WithArguments("E", "A").WithLocation(5, 14),
// (4,13): error CS0426: The type name 'D' does not exist in the type 'C'
// using X = C.D;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "D").WithArguments("D", "C").WithLocation(4, 13),
// (2,14): error CS0430: The extern alias 'A' was not specified in a /reference option
// extern alias A;
Diagnostic(ErrorCode.ERR_BadExternAlias, "A").WithArguments("A").WithLocation(2, 14),
// (3,7): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// using B;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(3, 7),
// (5,1): hidden CS8019: Unnecessary using directive.
// using Y = A::E;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Y = A::E;").WithLocation(5, 1),
// (3,1): hidden CS8019: Unnecessary using directive.
// using B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using B;").WithLocation(3, 1),
// (4,1): hidden CS8019: Unnecessary using directive.
// using X = C.D;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = C.D;").WithLocation(4, 1),
// (6,1): hidden CS8019: Unnecessary using directive.
// using Z = F<int>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Z = F<int>;").WithLocation(6, 1)
);
}
[Fact]
public void EmittingPdbVsNot()
{
string source = @"
using System;
using X = System.IO.FileStream;
class C
{
int x = 1;
static int y = 1;
C()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(source, assemblyName: "EmittingPdbVsNot", options: TestOptions.ReleaseDll);
var peStream1 = new MemoryStream();
var peStream2 = new MemoryStream();
var pdbStream = new MemoryStream();
c.Emit(peStream: peStream1, pdbStream: pdbStream);
c.Emit(peStream: peStream2);
MetadataValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void ImportedNoPiaTypes()
{
var sourceLib = @"
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: Guid(""11111111-1111-1111-1111-111111111111"")]
[assembly: ImportedFromTypeLib(""Goo"")]
[assembly: TypeLibVersion(1, 0)]
namespace N
{
public enum E
{
Value1 = 1
}
public struct S1
{
public int A1;
public int A2;
}
public struct S2
{
public const int Value2 = 2;
}
public struct SBad
{
public int A3;
public const int Value3 = 3;
}
[ComImport, Guid(""22222222-2222-2222-2222-222222222222"")]
public interface I
{
void F();
}
public interface IBad
{
void F();
}
}
";
var source = @"
using System;
using static N.E;
using static N.SBad;
using Z1 = N.S1;
using Z2 = N.S2;
using ZBad = N.SBad;
using NI = N.I;
using NIBad = N.IBad;
class C
{
NI i;
void M()
{
Console.WriteLine(Value1);
Console.WriteLine(Z2.Value2);
Console.WriteLine(new Z1());
}
}
";
var libRef = CreateCompilation(sourceLib, assemblyName: "ImportedNoPiaTypesAssemblyName").EmitToImageReference(embedInteropTypes: true);
var compilation = CreateCompilation(source, new[] { libRef });
var v = CompileAndVerify(compilation);
v.Diagnostics.Verify(
// (14,8): warning CS0169: The field 'C.i' is never used
// NI i;
Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("C.i"),
// (5,1): hidden CS8019: Unnecessary using directive.
// using static N.SBad;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N.SBad;"),
// (10,1): hidden CS8019: Unnecessary using directive.
// using NIBad = N.IBad;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NIBad = N.IBad;"),
// (8,1): hidden CS8019: Unnecessary using directive.
// using ZBad = N.SBad;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ZBad = N.SBad;"));
// Usings of embedded types are currently omitted:
v.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0xb"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""38"" document=""1"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""37"" document=""1"" />
<entry offset=""0x24"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void ImportedTypeWithUnknownBase()
{
var sourceLib1 = @"
namespace N
{
public class A { }
}
";
var sourceLib2 = @"
namespace N
{
public class B : A { }
}
";
var source = @"
using System;
using X = N.B;
class C
{
void M()
{
Console.WriteLine();
}
}
";
var libRef1 = CreateCompilation(sourceLib1).EmitToImageReference();
var libRef2 = CreateCompilation(sourceLib2, new[] { libRef1 }, assemblyName: "LibRef2").EmitToImageReference();
var compilation = CreateCompilation(source, new[] { libRef2 });
var v = CompileAndVerify(compilation);
v.Diagnostics.Verify(
// (3,1): hidden CS8019: Unnecessary using directive.
// using X = N.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = N.B;"));
v.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x5"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
<alias name=""X"" target=""N.B, LibRef2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportScopeEquality()
{
var sources = new[] { @"
extern alias A;
using System;
using C = System;
namespace N.M
{
using System.Collections;
class C1 { void F() {} }
}
namespace N.M
{
using System.Collections;
class C2 { void F() {} }
}
", @"
extern alias A;
using System;
using C = System;
namespace N.M
{
using System.Collections;
class C3 { void F() {} }
}
namespace N.M
{
using System.Collections.Generic;
class C4 { void F() {} }
}
", @"
extern alias A;
using System;
using D = System;
namespace N.M
{
using System.Collections;
class C5 { void F() {} }
}
", @"
extern alias A;
using System;
class C6 { void F() {} }
" };
var c = CreateCompilationWithMscorlib40(sources, new[] { SystemCoreRef.WithAliases(ImmutableArray.Create("A")) });
var pdbStream = new MemoryStream();
c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);
var pdbImage = pdbStream.ToImmutable();
using var metadata = new PinnedMetadata(pdbImage);
var mdReader = metadata.Reader;
var writer = new StringWriter();
var mdVisualizer = new MetadataVisualizer(mdReader, writer, MetadataVisualizerOptions.NoHeapReferences);
mdVisualizer.WriteImportScope();
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
ImportScope (index: 0x35, size: 36):
========================================================================
Parent Imports
========================================================================
1: nil (ImportScope) 'A' = 0x23000002 (AssemblyRef)
2: 0x35000001 (ImportScope) Extern Alias 'A', 'System'
3: 0x35000001 (ImportScope) Extern Alias 'A', 'System', 'C' = 'System'
4: 0x35000003 (ImportScope) nil
5: 0x35000004 (ImportScope) 'System.Collections'
6: 0x35000004 (ImportScope) 'System.Collections.Generic'
7: 0x35000001 (ImportScope) Extern Alias 'A', 'System', 'D' = 'System'
8: 0x35000007 (ImportScope) nil
9: 0x35000008 (ImportScope) 'System.Collections'
", writer.ToString());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.Metadata.Tools;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBUsingTests : CSharpPDBTestBase
{
#region Helpers
private static CSharpCompilation CreateDummyCompilation(string assemblyName)
{
return CreateCompilation(
"public class C { }",
assemblyName: assemblyName,
options: TestOptions.DebugDll);
}
#endregion
[Fact]
public void TestUsings()
{
var text = @"
using System;
class A { void M() { } }
namespace X
{
using System.IO;
class B { void M() { } }
namespace Y
{
using System.Threading;
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System.IO"" />
<namespace name=""System"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System.Threading"" />
<namespace name=""System.IO"" />
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestNamespaceAliases()
{
var text = @"
using P = System;
class A { void M() { } }
namespace X
{
using Q = System.IO;
class B { void M() { } }
namespace Y
{
using R = System.Threading;
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""Q"" target=""System.IO"" kind=""namespace"" />
<alias name=""P"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""R"" target=""System.Threading"" kind=""namespace"" />
<alias name=""Q"" target=""System.IO"" kind=""namespace"" />
<alias name=""P"" target=""System"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestTypeAliases1()
{
var text = @"
using P = System.String;
class A { void M() { } }
namespace X
{
using Q = System.Int32;
class B { void M() { } }
namespace Y
{
using R = System.Char;
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""Q"" target=""System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""R"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""Q"" target=""System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestTypeAliases2()
{
var text = @"
using P = System.Collections.Generic.List<int>;
class A { void M() { } }
namespace X
{
using Q = System.Collections.Generic.List<System.Collections.Generic.List<char>>;
class B { void M() { } }
namespace Y
{
using P = System.Char; //hides previous P
class C { void M() { } }
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""Q"" target=""System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""P"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""Q"" target=""System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""P"" target=""System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestExternAliases1()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
var text = @"
extern alias P;
class A { void M() { } }
namespace X
{
extern alias Q;
class B { void M() { } }
namespace Y
{
extern alias R;
class C { void M() { } }
}
}
";
var compilation = CreateCompilation(text,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")) ,
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R"))
});
compilation.VerifyDiagnostics(
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (8,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"),
// (14,9): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""22"" endLine=""4"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""P"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""24"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<extern alias=""P"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
<namespace usingCount=""1"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""30"" endLine=""16"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<extern alias=""Q"" />
<extern alias=""P"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(1120579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120579")]
public void TestExternAliases2()
{
string source1 = @"
namespace U.V.W {}
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, assemblyName: "TestExternAliases2");
string source2 = @"
using U.V.W;
class A { void M() { } }
";
var compilation2 = CreateCompilation(
source2,
options: TestOptions.DebugDll,
references: new[]
{
// first unaliased reference
compilation1.ToMetadataReference(),
// second aliased reference
compilation1.ToMetadataReference(ImmutableArray.Create("X"))
});
compilation2.VerifyPdb("A.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""23"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""U.V.W"" />
<externinfo alias=""X"" assembly=""TestExternAliases2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(1120579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120579")]
public void TestExternAliases3()
{
string source1 = @"
namespace U.V.W {}
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll, assemblyName: "TestExternAliases3");
string source2 = @"
using U.V.W;
class A { void M() { } }
";
var compilation2 = CreateCompilation(
source2,
options: TestOptions.DebugDll,
references: new[]
{
// first aliased reference
compilation1.ToMetadataReference(ImmutableArray.Create("X")),
// second unaliased reference
compilation1.ToMetadataReference(),
});
compilation2.VerifyPdb("A.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""20"" endLine=""4"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""23"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""U.V.W"" />
<externinfo alias=""X"" assembly=""TestExternAliases3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ExternAliases4()
{
var src1 = @"
namespace N
{
public class C { }
}";
var dummyCompilation = CreateCompilation(src1, assemblyName: "A", options: TestOptions.DebugDll);
var src2 = @"
namespace M
{
extern alias A;
using A::N;
public class D
{
public C P
{
get { return new C(); }
set { }
}
}
}";
var compilation = CreateCompilation(src2,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation, ImmutableArray.Create("A", "A")),
});
compilation.VerifyDiagnostics();
compilation.VerifyEmitDiagnostics();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestExternAliases_ExplicitAndGlobal()
{
var dummySource = @"
namespace N
{
public class C { }
}
";
CSharpCompilation dummyCompilation1 = CreateCompilation(dummySource, assemblyName: "A", options: TestOptions.DebugDll);
CSharpCompilation dummyCompilation2 = CreateCompilation(dummySource, assemblyName: "B", options: TestOptions.DebugDll);
var text = @"
extern alias A;
extern alias B;
using X = A::N;
using Y = B::N;
using Z = global::N;
class C { void M() { } }
";
var compilation = CreateCompilation(text,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("global", "A")),
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("B", "global"))
});
compilation.VerifyDiagnostics(
// (5,1): hidden CS8019: Unnecessary using directive.
// using Y = B::N;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Y = B::N;").WithLocation(5, 1),
// (4,1): hidden CS8019: Unnecessary using directive.
// using X = A::N;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = A::N;").WithLocation(4, 1),
// (6,1): hidden CS8019: Unnecessary using directive.
// using Z = global::N;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Z = global::N;").WithLocation(6, 1));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""5""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""20"" endLine=""8"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""A""/>
<extern alias=""B""/>
<alias name=""X"" target=""N"" kind=""namespace""/>
<alias name=""Y"" target=""N"" kind=""namespace""/>
<alias name=""Z"" target=""N"" kind=""namespace""/>
<externinfo alias=""A"" assembly=""A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""/>
<externinfo alias=""B"" assembly=""B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""/>
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestExternAliasesInUsing()
{
CSharpCompilation libComp = CreateCompilation(@"
namespace N
{
public class A { }
}", assemblyName: "Lib");
var text = @"
extern alias P;
using P::N;
using Q = P::N.A;
using R = P::N;
using global::N;
using S = global::N.B;
using T = global::N;
namespace N
{
class B { void M() { } }
}
";
var compilation = CreateCompilation(text,
assemblyName: "Test",
options: TestOptions.DebugDll,
references: new[] { new CSharpCompilationReference(libComp, ImmutableArray.Create("P")) });
compilation.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""N.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""7"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""26"" endLine=""12"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""P"" />
<namespace qualifier=""P"" name=""N"" />
<namespace name=""N"" />
<alias name=""Q"" target=""N.A, Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""R"" qualifier=""P"" target=""N"" kind=""namespace"" />
<alias name=""S"" target=""N.B"" kind=""type"" />
<alias name=""T"" target=""N"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestNamespacesAndAliases()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
var text = @"
extern alias P;
using System;
using AU1 = System;
using AT1 = System.Char;
class A { void M() { } }
namespace X
{
extern alias Q;
using AU2 = System.IO;
using AT2 = System.IO.Directory;
using System.IO;
class B { void M() { } }
namespace Y
{
extern alias R;
using AT3 = System.Text.StringBuilder;
using System.Text;
using AU3 = System.Text;
class C { void M() { } }
}
}
";
var compilation = CreateCompilation(text,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")) ,
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R"))
});
compilation.VerifyDiagnostics(
// (3,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU1 = System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU1 = System;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT1 = System.Char;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT1 = System.Char;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (12,5): info CS8019: Unnecessary using directive.
// using AU2 = System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU2 = System.IO;"),
// (13,5): info CS8019: Unnecessary using directive.
// using AT2 = System.IO.Directory;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT2 = System.IO.Directory;"),
// (14,5): info CS8019: Unnecessary using directive.
// using System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.IO;"),
// (11,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"),
// (21,9): info CS8019: Unnecessary using directive.
// using AT3 = System.Text.StringBuilder;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT3 = System.Text.StringBuilder;"),
// (22,9): info CS8019: Unnecessary using directive.
// using System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Text;"),
// (23,9): info CS8019: Unnecessary using directive.
// using AU3 = System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU3 = System.Text;"),
// (20,9): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""A"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""21"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.B"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""24"" endLine=""16"" endColumn=""25"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""26"" endLine=""16"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.Y.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""A"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""25"" startColumn=""28"" endLine=""25"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""25"" startColumn=""30"" endLine=""25"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<namespace name=""System.Text"" />
<alias name=""AT3"" target=""System.Text.StringBuilder, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Text"" kind=""namespace"" />
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737"), WorkItem(913022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913022")]
public void ReferenceWithMultipleAliases()
{
var source1 = @"
namespace N { public class D { } }
namespace M { public class E { } }
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var source2 = @"
extern alias A;
extern alias B;
using A::N;
using B::M;
using X = A::N;
using Y = B::N;
public class C
{
public static void Main()
{
System.Console.WriteLine(new D());
System.Console.WriteLine(new E());
System.Console.WriteLine(new X.D());
System.Console.WriteLine(new Y.D());
}
}";
var compilation2 = CreateCompilation(source2,
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(compilation1, ImmutableArray.Create("A", "B"))
});
compilation2.VerifyDiagnostics();
compilation2.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""6""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""43"" document=""1"" />
<entry offset=""0xc"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""43"" document=""1"" />
<entry offset=""0x17"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""45"" document=""1"" />
<entry offset=""0x22"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""45"" document=""1"" />
<entry offset=""0x2d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<extern alias=""A""/>
<extern alias=""B""/>
<namespace qualifier=""A"" name=""N""/>
<namespace qualifier=""A"" name=""M""/>
<alias name=""X"" qualifier=""A"" target=""N"" kind=""namespace""/>
<alias name=""Y"" qualifier=""A"" target=""N"" kind=""namespace""/>
<externinfo alias = ""A"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias = ""B"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(913022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913022")]
public void ReferenceWithGlobalAndDuplicateAliases()
{
var source1 = @"
namespace N { public class D { } }
";
var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var source2 = @"
extern alias A;
extern alias B;
public class C
{
public static void Main()
{
System.Console.WriteLine(new N.D());
System.Console.WriteLine(new A::N.D());
System.Console.WriteLine(new B::N.D());
}
}";
var compilation2 = CreateCompilation(source2,
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(compilation1, ImmutableArray.Create("global", "B", "A", "A", "global"))
});
compilation2.VerifyDiagnostics();
compilation2.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""45"" document=""1"" />
<entry offset=""0xc"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""48"" document=""1"" />
<entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""48"" document=""1"" />
<entry offset=""0x22"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x23"">
<extern alias=""A"" />
<extern alias=""B"" />
<externinfo alias=""B"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""A"" assembly=""" + compilation1.AssemblyName + @", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestPartialTypeInOneFile()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
var text1 = @"
extern alias P;
using System;
using AU1 = System;
using AT1 = System.Char;
namespace X
{
extern alias Q;
using AU2 = System.IO;
using AT2 = System.IO.Directory;
using System.IO;
partial class C
{
partial void M();
void N1() { }
}
}
namespace X
{
extern alias R;
using AU3 = System.Threading;
using AT3 = System.Threading.Thread;
using System.Threading;
partial class C
{
partial void M() { }
void N2() { }
}
}
";
var compilation = CreateCompilation(
text1,
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")),
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R")),
});
compilation.VerifyDiagnostics(
// (3,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU1 = System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU1 = System;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT1 = System.Char;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT1 = System.Char;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (24,5): info CS8019: Unnecessary using directive.
// using AU3 = System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU3 = System.Threading;"),
// (25,5): info CS8019: Unnecessary using directive.
// using AT3 = System.Threading.Thread;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT3 = System.Threading.Thread;"),
// (26,5): info CS8019: Unnecessary using directive.
// using System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading;"),
// (23,5): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"),
// (10,5): info CS8019: Unnecessary using directive.
// using AU2 = System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU2 = System.IO;"),
// (11,5): info CS8019: Unnecessary using directive.
// using AT2 = System.IO.Directory;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT2 = System.IO.Directory;"),
// (12,5): info CS8019: Unnecessary using directive.
// using System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.IO;"),
// (9,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""X.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""27"" document=""1"" />
<entry offset=""0x1"" startLine=""30"" startColumn=""28"" endLine=""30"" endColumn=""29"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<namespace name=""System.Threading"" />
<alias name=""AT3"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.C"" name=""N1"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.C"" name=""N2"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""31"" startColumn=""19"" endLine=""31"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""31"" startColumn=""21"" endLine=""31"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""R"" />
<namespace name=""System.Threading"" />
<alias name=""AT3"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>", options: PdbValidationOptions.SkipConversionValidation); // TODO: https://github.com/dotnet/roslyn/issues/18004
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestPartialTypeInTwoFiles()
{
CSharpCompilation dummyCompilation1 = CreateDummyCompilation("a");
CSharpCompilation dummyCompilation2 = CreateDummyCompilation("b");
CSharpCompilation dummyCompilation3 = CreateDummyCompilation("c");
CSharpCompilation dummyCompilation4 = CreateDummyCompilation("d");
var text1 = @"
extern alias P;
using System;
using AU1 = System;
using AT1 = System.Char;
namespace X
{
extern alias Q;
using AU2 = System.IO;
using AT2 = System.IO.Directory;
using System.IO;
partial class C
{
partial void M();
void N1() { }
}
}
";
var text2 = @"
extern alias R;
using System.Text;
using AU3 = System.Text;
using AT3 = System.Text.StringBuilder;
namespace X
{
extern alias S;
using AU4 = System.Threading;
using AT4 = System.Threading.Thread;
using System.Threading;
partial class C
{
partial void M() { }
void N2() { }
}
}
";
var compilation = CreateCompilation(
new string[] { text1, text2 },
assemblyName: GetUniqueName(),
options: TestOptions.DebugDll,
references: new[]
{
new CSharpCompilationReference(dummyCompilation1, ImmutableArray.Create("P")),
new CSharpCompilationReference(dummyCompilation2, ImmutableArray.Create("Q")),
new CSharpCompilationReference(dummyCompilation3, ImmutableArray.Create("R")),
new CSharpCompilationReference(dummyCompilation4, ImmutableArray.Create("S")),
});
compilation.VerifyDiagnostics(
// (3,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU1 = System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU1 = System;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT1 = System.Char;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT1 = System.Char;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias P;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias P;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Text;"),
// (4,1): info CS8019: Unnecessary using directive.
// using AU3 = System.Text;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU3 = System.Text;"),
// (5,1): info CS8019: Unnecessary using directive.
// using AT3 = System.Text.StringBuilder;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT3 = System.Text.StringBuilder;"),
// (10,5): info CS8019: Unnecessary using directive.
// using AU2 = System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU2 = System.IO;"),
// (2,1): info CS8020: Unused extern alias.
// extern alias R;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias R;"),
// (11,5): info CS8019: Unnecessary using directive.
// using AT2 = System.IO.Directory;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT2 = System.IO.Directory;"),
// (12,5): info CS8019: Unnecessary using directive.
// using System.IO;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.IO;"),
// (10,5): info CS8019: Unnecessary using directive.
// using AU4 = System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AU4 = System.Threading;"),
// (9,5): info CS8020: Unused extern alias.
// extern alias Q;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias Q;"),
// (11,5): info CS8019: Unnecessary using directive.
// using AT4 = System.Threading.Thread;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using AT4 = System.Threading.Thread;"),
// (12,5): info CS8019: Unnecessary using directive.
// using System.Threading;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading;"),
// (9,5): info CS8020: Unused extern alias.
// extern alias S;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias S;"));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""X.C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""26"" endLine=""16"" endColumn=""27"" document=""1"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""28"" endLine=""16"" endColumn=""29"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""S"" />
<namespace name=""System.Threading"" />
<alias name=""AT4"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU4"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""R"" />
<namespace name=""System.Text"" />
<alias name=""AT3"" target=""System.Text.StringBuilder, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Text"" kind=""namespace"" />
<externinfo alias=""P"" assembly=""a, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""Q"" assembly=""b, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""R"" assembly=""c, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<externinfo alias=""S"" assembly=""d, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
<method containingType=""X.C"" name=""N1"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""Q"" />
<namespace name=""System.IO"" />
<alias name=""AT2"" target=""System.IO.Directory, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU2"" target=""System.IO"" kind=""namespace"" />
<extern alias=""P"" />
<namespace name=""System"" />
<alias name=""AT1"" target=""System.Char, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU1"" target=""System"" kind=""namespace"" />
</scope>
</method>
<method containingType=""X.C"" name=""N2"">
<customDebugInfo>
<using>
<namespace usingCount=""4"" />
<namespace usingCount=""4"" />
</using>
<forwardToModule declaringType=""X.C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<extern alias=""S"" />
<namespace name=""System.Threading"" />
<alias name=""AT4"" target=""System.Threading.Thread, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU4"" target=""System.Threading"" kind=""namespace"" />
<extern alias=""R"" />
<namespace name=""System.Text"" />
<alias name=""AT3"" target=""System.Text.StringBuilder, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
<alias name=""AU3"" target=""System.Text"" kind=""namespace"" />
</scope>
</method>
</methods>
</symbols>", options: PdbValidationOptions.SkipConversionValidation); // TODO: https://github.com/dotnet/roslyn/issues/18004
}
[Fact]
public void TestSynthesizedConstructors()
{
var text = @"
namespace X
{
using System;
partial class C
{
int x = 1;
static int sx = 1;
}
}
namespace X
{
using System.IO;
partial class C
{
int y = 1;
static int sy = 1;
}
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""X.C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1""/>
<namespace usingCount=""0""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0x7"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""19"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<namespace name=""System""/>
</scope>
</method>
<method containingType=""X.C"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""X.C"" methodName="".ctor""/>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" />
<entry offset=""0x6"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""27"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestFieldInitializerLambdas()
{
var text = WithWindowsLineBreaks(@"
using System.Linq;
class C
{
int x = new int[2].Count(x => { return x % 3 == 0; });
static bool sx = new int[2].Any(x =>
{
return x % 2 == 0;
});
}
");
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<lambda offset=""-23"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""59"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
</scope>
</method>
<method containingType=""C"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLambdaMap>
<methodOrdinal>3</methodOrdinal>
<lambda offset=""-38"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""10"" endColumn=""8"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__2_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""-23"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""35"" endLine=""6"" endColumn=""36"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""37"" endLine=""6"" endColumn=""55"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""56"" endLine=""6"" endColumn=""57"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__3_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""-38"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" />
<entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestAccessors()
{
var text = WithWindowsLineBreaks(@"
using System;
class C
{
int P1 { get; set; }
int P2 { get { return 0; } set { } }
int this[int x] { get { return 0; } set { } }
event System.Action E1;
event System.Action E2 { add { } remove { } }
}
");
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P1"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""14"" endLine=""6"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_P1"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""19"" endLine=""6"" endColumn=""23"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_P2"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""29"" document=""1"" />
<entry offset=""0x5"" startLine=""7"" startColumn=""30"" endLine=""7"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""set_P2"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""36"" endLine=""7"" endColumn=""37"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""38"" endLine=""7"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_Item"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""28"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""29"" endLine=""8"" endColumn=""38"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""39"" endLine=""8"" endColumn=""40"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_Item"" parameterNames=""x, value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""8"" endColumn=""46"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""47"" endLine=""8"" endColumn=""48"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""add_E2"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""34"" endLine=""10"" endColumn=""35"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""36"" endLine=""10"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""remove_E2"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P2"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""46"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""47"" endLine=""10"" endColumn=""48"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSynthesizedSealedAccessors()
{
var text = @"
using System;
class Base
{
public virtual int P { get; set; }
}
class Derived : Base
{
public sealed override int P { set { } } //have to synthesize a sealed getter
}
";
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Base"" name=""get_P"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""28"" endLine=""6"" endColumn=""32"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Base"" name=""set_P"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Derived"" name=""set_P"" parameterNames=""value"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""40"" endLine=""11"" endColumn=""41"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""42"" endLine=""11"" endColumn=""43"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSynthesizedExplicitImplementation()
{
var text = WithWindowsLineBreaks(@"
using System.Runtime.CompilerServices;
interface I1
{
[IndexerName(""A"")]
int this[int x] { get; set; }
}
interface I2
{
[IndexerName(""B"")]
int this[int x] { get; set; }
}
class C : I1, I2
{
public int this[int x] { get { return 0; } set { } }
}
");
CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_Item"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""34"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""36"" endLine=""18"" endColumn=""45"" document=""1"" />
<entry offset=""0x5"" startLine=""18"" startColumn=""46"" endLine=""18"" endColumn=""47"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System.Runtime.CompilerServices"" />
</scope>
</method>
<method containingType=""C"" name=""set_Item"" parameterNames=""x, value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_Item"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""52"" endLine=""18"" endColumn=""53"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""54"" endLine=""18"" endColumn=""55"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(692496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/692496")]
[Fact]
public void SequencePointOnUsingExpression()
{
var source = @"
using System;
public class Test : IDisposable
{
static void Main()
{
using (new Test())
{
}
}
public void Dispose() { }
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Test.Main", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (Test V_0)
-IL_0000: nop
-IL_0001: newobj ""Test..ctor()""
IL_0006: stloc.0
.try
{
-IL_0007: nop
-IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
~IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
~IL_0015: endfinally
}
-IL_0016: ret
}", sequencePoints: "Test.Main");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestNestedType()
{
var libSource = @"
public class Outer
{
public class Inner
{
}
}
";
var libRef = CreateCompilation(libSource, assemblyName: "Lib").EmitToImageReference();
var source = @"
using I = Outer.Inner;
public class Test
{
static void Main()
{
}
}
";
CompileAndVerify(source, new[] { libRef }, options: TestOptions.DebugExe).VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""Test"" methodName=""Main"" />
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""I"" target=""Outer+Inner, Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void TestVerbatimIdentifiers()
{
var source = @"
using @namespace;
using @object = @namespace;
using @string = @namespace.@class<@namespace.@interface>.@struct;
namespace @namespace
{
public class @class<T>
{
public struct @struct
{
}
}
public interface @interface
{
}
}
class Test { static void Main() { } }
";
var comp = CreateCompilation(source);
// As in dev12, we drop all '@'s.
comp.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""20"" startColumn=""35"" endLine=""20"" endColumn=""36"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1"">
<namespace name=""namespace"" />
<alias name=""object"" target=""namespace"" kind=""namespace"" />
<alias name=""string"" target=""namespace.class`1+struct[namespace.interface]"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(842479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842479")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void UsingExternAlias()
{
var libSource = "public class C { }";
var lib = CreateCompilation(libSource, assemblyName: "Lib");
var libRef = lib.EmitToImageReference(aliases: ImmutableArray.Create("Q"));
var source = @"
extern alias Q;
using R = Q;
using Q;
namespace N
{
using S = R;
using R;
class D
{
static void Main() { }
}
}
";
var comp = CreateCompilation(source, new[] { libRef });
comp.VerifyPdb("N.D.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""N.D"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
<namespace usingCount=""3"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""30"" endLine=""13"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1"">
<namespace qualifier=""Q"" name="""" />
<alias name=""S"" qualifier=""Q"" target="""" kind=""namespace"" />
<extern alias=""Q"" />
<namespace qualifier=""Q"" name="""" />
<alias name=""R"" qualifier=""Q"" target="""" kind=""namespace"" />
<externinfo alias=""Q"" assembly=""Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(842478, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842478")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void AliasIncludingDynamic()
{
var source = @"
using AD = System.Action<dynamic>;
class D
{
static void Main() { }
}
";
var comp = CreateCompilation(source);
comp.VerifyPdb("D.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""D"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""26"" endLine=""6"" endColumn=""27"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1"">
<alias name=""AD"" target=""System.Action`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UsingExpression()
{
TestSequencePoints(
@"using System;
public class Test : IDisposable
{
static void Main()
{
[|using (new Test())|]
{
}
}
public void Dispose() { }
}", TestOptions.ReleaseExe, methodName: "Test.Main");
}
[Fact]
public void UsingVariable()
{
TestSequencePoints(
@"using System;
public class Test : IDisposable
{
static void Main()
{
var x = new Test();
[|using (x)|]
{
}
}
public void Dispose() { }
}", TestOptions.ReleaseExe, methodName: "Test.Main");
}
[WorkItem(546754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546754")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void ArrayType()
{
var source1 = @"
using System;
public class W {}
public class Y<T>
{
public class F {}
public class Z<U> {}
}
";
var comp1 = CreateCompilation(source1, options: TestOptions.DebugDll, assemblyName: "Comp1");
var source2 = @"
using t1 = Y<W[]>;
using t2 = Y<W[,]>;
using t3 = Y<W[,][]>;
using t4 = Y<Y<W>[][,]>;
using t5 = Y<W[,][]>.Z<W[][,,]>;
using t6 = Y<Y<Y<int[]>.F[,][]>.Z<Y<W[,][]>.F[]>[][]>;
public class C1
{
public static void Main()
{
}
}
";
var comp2 = CreateCompilation(source2, new[] { comp1.ToMetadataReference() }, options: TestOptions.DebugExe);
comp2.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C1"" methodName=""Main"" />
<methods>
<method containingType=""C1"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""6"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<alias name=""t1"" target=""Y`1[[W[], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t2"" target=""Y`1[[W[,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t3"" target=""Y`1[[W[][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t4"" target=""Y`1[[Y`1[[W, Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]][,][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t5"" target=""Y`1+Z`1[[W[][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[W[,,][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
<alias name=""t6"" target=""Y`1[[Y`1+Z`1[[Y`1+F[[System.Int32[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[Y`1+F[[W[][,], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]][][], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], Comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737"), WorkItem(543615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615")]
public void WRN_DebugFullNameTooLong()
{
var text = @"
using System;
using DICT1 = System.Collections.Generic.Dictionary<int, int>;
namespace goo
{
using ACT = System.Action<DICT1, DICT1, DICT1, DICT1, DICT1, DICT1, DICT1>;
class C
{
static void Main()
{
ACT ac = null;
Console.Write(ac);
}
}
}";
var compilation = CreateCompilation(text, options: TestOptions.DebugExe);
var exebits = new MemoryStream();
var pdbbits = new MemoryStream();
var result = compilation.Emit(exebits, pdbbits);
result.Diagnostics.Verify(
Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, "Main").WithArguments("AACT TSystem.Action`7[[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
}
[WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")]
[Fact]
public void StaticType()
{
var source = @"
using static System.Math;
class D
{
static void Main()
{
Max(1, 2);
}
}
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40);
comp.VerifyPdb("D.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""D"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1""/>
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0x8"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<type name=""System.Math, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""/>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UnusedImports()
{
var source = @"
extern alias A;
using System;
using X = A::System.Linq.Enumerable;
using Y = A::System.Linq;
using Z = System.Data.DataColumn;
using F = System.Func<int>;
class C
{
static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemCoreRef.WithAliases(new[] { "A" }), SystemDataRef });
var v = CompileAndVerify(comp, validator: (peAssembly) =>
{
var reader = peAssembly.ManifestModule.MetadataReader;
Assert.Equal(new[]
{
"mscorlib",
"System.Core",
"System.Data"
}, peAssembly.AssemblyReferences.Select(ai => ai.Name));
Assert.Equal(new[]
{
"CompilationRelaxationsAttribute",
"RuntimeCompatibilityAttribute",
"DebuggableAttribute",
"DebuggingModes",
"Object",
"Func`1",
"Enumerable",
"DataColumn"
}, reader.TypeReferences.Select(h => reader.GetString(reader.GetTypeReference(h).Name)));
Assert.Equal(1, reader.GetTableRowCount(TableIndex.TypeSpec));
});
}
[Fact]
public void UnusedImports_Nonexisting()
{
var source = @"
extern alias A;
using B;
using X = C.D;
using Y = A::E;
using Z = F<int>;
class C
{
static void Main()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,11): error CS0246: The type or namespace name 'F<>' could not be found (are you missing a using directive or an assembly reference?)
// using Z = F<int>;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "F<int>").WithArguments("F<>").WithLocation(6, 11),
// (5,14): error CS0234: The type or namespace name 'E' does not exist in the namespace 'A' (are you missing an assembly reference?)
// using Y = A::E;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "E").WithArguments("E", "A").WithLocation(5, 14),
// (4,13): error CS0426: The type name 'D' does not exist in the type 'C'
// using X = C.D;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "D").WithArguments("D", "C").WithLocation(4, 13),
// (2,14): error CS0430: The extern alias 'A' was not specified in a /reference option
// extern alias A;
Diagnostic(ErrorCode.ERR_BadExternAlias, "A").WithArguments("A").WithLocation(2, 14),
// (3,7): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// using B;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(3, 7),
// (5,1): hidden CS8019: Unnecessary using directive.
// using Y = A::E;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Y = A::E;").WithLocation(5, 1),
// (3,1): hidden CS8019: Unnecessary using directive.
// using B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using B;").WithLocation(3, 1),
// (4,1): hidden CS8019: Unnecessary using directive.
// using X = C.D;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = C.D;").WithLocation(4, 1),
// (6,1): hidden CS8019: Unnecessary using directive.
// using Z = F<int>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Z = F<int>;").WithLocation(6, 1)
);
}
[Fact]
public void EmittingPdbVsNot()
{
string source = @"
using System;
using X = System.IO.FileStream;
class C
{
int x = 1;
static int y = 1;
C()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(source, assemblyName: "EmittingPdbVsNot", options: TestOptions.ReleaseDll);
var peStream1 = new MemoryStream();
var peStream2 = new MemoryStream();
var pdbStream = new MemoryStream();
c.Emit(peStream: peStream1, pdbStream: pdbStream);
c.Emit(peStream: peStream2);
MetadataValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void ImportedNoPiaTypes()
{
var sourceLib = @"
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: Guid(""11111111-1111-1111-1111-111111111111"")]
[assembly: ImportedFromTypeLib(""Goo"")]
[assembly: TypeLibVersion(1, 0)]
namespace N
{
public enum E
{
Value1 = 1
}
public struct S1
{
public int A1;
public int A2;
}
public struct S2
{
public const int Value2 = 2;
}
public struct SBad
{
public int A3;
public const int Value3 = 3;
}
[ComImport, Guid(""22222222-2222-2222-2222-222222222222"")]
public interface I
{
void F();
}
public interface IBad
{
void F();
}
}
";
var source = @"
using System;
using static N.E;
using static N.SBad;
using Z1 = N.S1;
using Z2 = N.S2;
using ZBad = N.SBad;
using NI = N.I;
using NIBad = N.IBad;
class C
{
NI i;
void M()
{
Console.WriteLine(Value1);
Console.WriteLine(Z2.Value2);
Console.WriteLine(new Z1());
}
}
";
var libRef = CreateCompilation(sourceLib, assemblyName: "ImportedNoPiaTypesAssemblyName").EmitToImageReference(embedInteropTypes: true);
var compilation = CreateCompilation(source, new[] { libRef });
var v = CompileAndVerify(compilation);
v.Diagnostics.Verify(
// (14,8): warning CS0169: The field 'C.i' is never used
// NI i;
Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("C.i"),
// (5,1): hidden CS8019: Unnecessary using directive.
// using static N.SBad;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N.SBad;"),
// (10,1): hidden CS8019: Unnecessary using directive.
// using NIBad = N.IBad;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NIBad = N.IBad;"),
// (8,1): hidden CS8019: Unnecessary using directive.
// using ZBad = N.SBad;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ZBad = N.SBad;"));
// Usings of embedded types are currently omitted:
v.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0xb"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""38"" document=""1"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""37"" document=""1"" />
<entry offset=""0x24"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/25737")]
public void ImportedTypeWithUnknownBase()
{
var sourceLib1 = @"
namespace N
{
public class A { }
}
";
var sourceLib2 = @"
namespace N
{
public class B : A { }
}
";
var source = @"
using System;
using X = N.B;
class C
{
void M()
{
Console.WriteLine();
}
}
";
var libRef1 = CreateCompilation(sourceLib1).EmitToImageReference();
var libRef2 = CreateCompilation(sourceLib2, new[] { libRef1 }, assemblyName: "LibRef2").EmitToImageReference();
var compilation = CreateCompilation(source, new[] { libRef2 });
var v = CompileAndVerify(compilation);
v.Diagnostics.Verify(
// (3,1): hidden CS8019: Unnecessary using directive.
// using X = N.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = N.B;"));
v.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x5"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
<alias name=""X"" target=""N.B, LibRef2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" kind=""type"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportScopeEquality()
{
var sources = new[] { @"
extern alias A;
using System;
using C = System;
namespace N.M
{
using System.Collections;
class C1 { void F() {} }
}
namespace N.M
{
using System.Collections;
class C2 { void F() {} }
}
", @"
extern alias A;
using System;
using C = System;
namespace N.M
{
using System.Collections;
class C3 { void F() {} }
}
namespace N.M
{
using System.Collections.Generic;
class C4 { void F() {} }
}
", @"
extern alias A;
using System;
using D = System;
namespace N.M
{
using System.Collections;
class C5 { void F() {} }
}
", @"
extern alias A;
using System;
class C6 { void F() {} }
" };
var c = CreateCompilationWithMscorlib40(sources, new[] { SystemCoreRef.WithAliases(ImmutableArray.Create("A")) });
var pdbStream = new MemoryStream();
c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);
var pdbImage = pdbStream.ToImmutable();
using var metadata = new PinnedMetadata(pdbImage);
var mdReader = metadata.Reader;
var writer = new StringWriter();
var mdVisualizer = new MetadataVisualizer(mdReader, writer, MetadataVisualizerOptions.NoHeapReferences);
mdVisualizer.WriteImportScope();
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
ImportScope (index: 0x35, size: 36):
========================================================================
Parent Imports
========================================================================
1: nil (ImportScope) 'A' = 0x23000002 (AssemblyRef)
2: 0x35000001 (ImportScope) Extern Alias 'A', 'System'
3: 0x35000001 (ImportScope) Extern Alias 'A', 'System', 'C' = 'System'
4: 0x35000003 (ImportScope) nil
5: 0x35000004 (ImportScope) 'System.Collections'
6: 0x35000004 (ImportScope) 'System.Collections.Generic'
7: 0x35000001 (ImportScope) Extern Alias 'A', 'System', 'D' = 'System'
8: 0x35000007 (ImportScope) nil
9: 0x35000008 (ImportScope) 'System.Collections'
", writer.ToString());
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Test.Next/Remote/RemoteHostClientServiceFactoryTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Remote.UnitTests
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.RemoteHost)]
public class RemoteHostClientServiceFactoryTests
{
private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess);
private static AdhocWorkspace CreateWorkspace()
=> new AdhocWorkspace(s_composition.GetHostServices());
[Fact]
public async Task UpdaterService()
{
var hostServices = s_composition.GetHostServices();
using var workspace = new AdhocWorkspace(hostServices);
var options = workspace.CurrentSolution.Options
.WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));
var listenerProvider = ((IMefHostExportProvider)hostServices).GetExportedValue<AsynchronousOperationListenerProvider>();
var checksumUpdater = new SolutionChecksumUpdater(workspace, listenerProvider, CancellationToken.None);
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
// make sure client is ready
using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
// add solution, change document
workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
var project = workspace.AddProject("proj", LanguageNames.CSharp);
var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));
workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None);
// wait for listener
var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
await workspaceListener.ExpeditedWaitAsync();
var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater);
await listener.ExpeditedWaitAsync();
// checksum should already exist
Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _));
checksumUpdater.Shutdown();
}
[Fact]
public async Task TestSessionWithNoSolution()
{
using var workspace = CreateWorkspace();
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
var mock = new MockLogService();
var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
using var connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(callbackTarget: mock);
Assert.True(await connection.TryInvokeAsync(
(service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, "emptySource", Path.GetTempPath(), cancellationToken),
CancellationToken.None));
}
[Fact]
public async Task TestSessionClosed()
{
using var workspace = CreateWorkspace();
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var serviceName = new RemoteServiceName("Test");
// register local service
TestService testService = null;
client.RegisterService(serviceName, (s, p, o) =>
{
testService = new TestService(s, p);
return testService;
});
// create session that stay alive until client alive (ex, SymbolSearchUpdateEngine)
using var connection = await client.CreateConnectionAsync(serviceName, callbackTarget: null, CancellationToken.None);
// mimic unfortunate call that happens to be in the middle of communication.
var task = connection.RunRemoteAsync("TestMethodAsync", solution: null, arguments: null, CancellationToken.None);
// make client to go away
client.Dispose();
// let the service to return
testService.Event.Set();
// make sure task finished gracefully
await task;
}
private class TestService : ServiceBase
{
public TestService(Stream stream, IServiceProvider serviceProvider)
: base(serviceProvider, stream)
{
Event = new ManualResetEvent(false);
StartService();
}
public readonly ManualResetEvent Event;
public Task TestMethodAsync()
{
Event.WaitOne();
return Task.CompletedTask;
}
}
private class NullAssemblyAnalyzerLoader : IAnalyzerAssemblyLoader
{
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
{
// doesn't matter what it returns
return typeof(object).Assembly;
}
}
private class MockLogService : ISymbolSearchLogService
{
public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => default;
public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => default;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Remote.UnitTests
{
[UseExportProvider]
[Trait(Traits.Feature, Traits.Features.RemoteHost)]
public class RemoteHostClientServiceFactoryTests
{
private static readonly TestComposition s_composition = FeaturesTestCompositions.Features.WithTestHostParts(TestHost.OutOfProcess);
private static AdhocWorkspace CreateWorkspace()
=> new AdhocWorkspace(s_composition.GetHostServices());
[Fact]
public async Task UpdaterService()
{
var hostServices = s_composition.GetHostServices();
using var workspace = new AdhocWorkspace(hostServices);
var options = workspace.CurrentSolution.Options
.WithChangedOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS, 1);
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));
var listenerProvider = ((IMefHostExportProvider)hostServices).GetExportedValue<AsynchronousOperationListenerProvider>();
var checksumUpdater = new SolutionChecksumUpdater(workspace, listenerProvider, CancellationToken.None);
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
// make sure client is ready
using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
// add solution, change document
workspace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default));
var project = workspace.AddProject("proj", LanguageNames.CSharp);
var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));
workspace.ApplyTextChanges(document.Id, new[] { new TextChange(new TextSpan(0, 1), "abc") }, CancellationToken.None);
// wait for listener
var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
await workspaceListener.ExpeditedWaitAsync();
var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater);
await listener.ExpeditedWaitAsync();
// checksum should already exist
Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _));
checksumUpdater.Shutdown();
}
[Fact]
public async Task TestSessionWithNoSolution()
{
using var workspace = CreateWorkspace();
var service = workspace.Services.GetRequiredService<IRemoteHostClientProvider>();
var mock = new MockLogService();
var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);
using var connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(callbackTarget: mock);
Assert.True(await connection.TryInvokeAsync(
(service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, "emptySource", Path.GetTempPath(), cancellationToken),
CancellationToken.None));
}
[Fact]
public async Task TestSessionClosed()
{
using var workspace = CreateWorkspace();
using var client = await InProcRemoteHostClient.GetTestClientAsync(workspace).ConfigureAwait(false);
var serviceName = new RemoteServiceName("Test");
// register local service
TestService testService = null;
client.RegisterService(serviceName, (s, p, o) =>
{
testService = new TestService(s, p);
return testService;
});
// create session that stay alive until client alive (ex, SymbolSearchUpdateEngine)
using var connection = await client.CreateConnectionAsync(serviceName, callbackTarget: null, CancellationToken.None);
// mimic unfortunate call that happens to be in the middle of communication.
var task = connection.RunRemoteAsync("TestMethodAsync", solution: null, arguments: null, CancellationToken.None);
// make client to go away
client.Dispose();
// let the service to return
testService.Event.Set();
// make sure task finished gracefully
await task;
}
private class TestService : ServiceBase
{
public TestService(Stream stream, IServiceProvider serviceProvider)
: base(serviceProvider, stream)
{
Event = new ManualResetEvent(false);
StartService();
}
public readonly ManualResetEvent Event;
public Task TestMethodAsync()
{
Event.WaitOne();
return Task.CompletedTask;
}
}
private class NullAssemblyAnalyzerLoader : IAnalyzerAssemblyLoader
{
public void AddDependencyLocation(string fullPath)
{
}
public Assembly LoadFromPath(string fullPath)
{
// doesn't matter what it returns
return typeof(object).Assembly;
}
}
private class MockLogService : ISymbolSearchLogService
{
public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => default;
public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => default;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Symbols/AnonymousTypes/CommonAnonymousTypeManager.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Symbols
{
internal abstract class CommonAnonymousTypeManager
{
/// <summary>
/// We should not see new anonymous types from source after we finished emit phase.
/// If this field is true, the collection is sealed; in DEBUG it also is used to check the assertion.
/// </summary>
private ThreeState _templatesSealed = ThreeState.False;
/// <summary>
/// Collection of anonymous type templates is sealed
/// </summary>
internal bool AreTemplatesSealed
{
get { return _templatesSealed == ThreeState.True; }
}
protected void SealTemplates()
{
_templatesSealed = ThreeState.True;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Symbols
{
internal abstract class CommonAnonymousTypeManager
{
/// <summary>
/// We should not see new anonymous types from source after we finished emit phase.
/// If this field is true, the collection is sealed; in DEBUG it also is used to check the assertion.
/// </summary>
private ThreeState _templatesSealed = ThreeState.False;
/// <summary>
/// Collection of anonymous type templates is sealed
/// </summary>
internal bool AreTemplatesSealed
{
get { return _templatesSealed == ThreeState.True; }
}
protected void SealTemplates()
{
_templatesSealed = ThreeState.True;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
/// <summary>
/// For the purpose of escape verification we operate with the depth of local scopes.
/// The depth is a uint, with smaller number representing shallower/wider scopes.
/// The 0 and 1 are special scopes -
/// 0 is the "external" or "return" scope that is outside of the containing method/lambda.
/// If something can escape to scope 0, it can escape to any scope in a given method or can be returned.
/// 1 is the "parameter" or "top" scope that is just inside the containing method/lambda.
/// If something can escape to scope 1, it can escape to any scope in a given method, but cannot be returned.
/// n + 1 corresponds to scopes immediately inside a scope of depth n.
/// Since sibling scopes do not intersect and a value cannot escape from one to another without
/// escaping to a wider scope, we can use simple depth numbering without ambiguity.
/// </summary>
internal const uint ExternalScope = 0;
internal const uint TopLevelScope = 1;
// Some value kinds are semantically the same and the only distinction is how errors are reported
// for those purposes we reserve lowest 2 bits
private const int ValueKindInsignificantBits = 2;
private const BindValueKind ValueKindSignificantBitsMask = unchecked((BindValueKind)~((1 << ValueKindInsignificantBits) - 1));
/// <summary>
/// Expression capabilities and requirements.
/// </summary>
[Flags]
internal enum BindValueKind : ushort
{
///////////////////
// All expressions can be classified according to the following 4 capabilities:
//
/// <summary>
/// Expression can be an RHS of an assignment operation.
/// </summary>
/// <remarks>
/// The following are rvalues: values, variables, null literals, properties
/// and indexers with getters, events.
///
/// The following are not rvalues:
/// namespaces, types, method groups, anonymous functions.
/// </remarks>
RValue = 1 << ValueKindInsignificantBits,
/// <summary>
/// Expression can be the LHS of a simple assignment operation.
/// Example:
/// property with a setter
/// </summary>
Assignable = 2 << ValueKindInsignificantBits,
/// <summary>
/// Expression represents a location. Often referred as a "variable"
/// Examples:
/// local variable, parameter, field
/// </summary>
RefersToLocation = 4 << ValueKindInsignificantBits,
/// <summary>
/// Expression can be the LHS of a ref-assign operation.
/// Example:
/// ref local, ref parameter, out parameter
/// </summary>
RefAssignable = 8 << ValueKindInsignificantBits,
///////////////////
// The rest are just combinations of the above.
//
/// <summary>
/// Expression is the RHS of an assignment operation
/// and may be a method group.
/// Basically an RValue, but could be treated differently for the purpose of error reporting
/// </summary>
RValueOrMethodGroup = RValue + 1,
/// <summary>
/// Expression can be an LHS of a compound assignment
/// operation (such as +=).
/// </summary>
CompoundAssignment = RValue | Assignable,
/// <summary>
/// Expression can be the operand of an increment or decrement operation.
/// Same as CompoundAssignment, the distinction is really just for error reporting.
/// </summary>
IncrementDecrement = CompoundAssignment + 1,
/// <summary>
/// Expression is a r/o reference.
/// </summary>
ReadonlyRef = RefersToLocation | RValue,
/// <summary>
/// Expression can be the operand of an address-of operation (&).
/// Same as ReadonlyRef. The difference is just for error reporting.
/// </summary>
AddressOf = ReadonlyRef + 1,
/// <summary>
/// Expression is the receiver of a fixed buffer field access
/// Same as ReadonlyRef. The difference is just for error reporting.
/// </summary>
FixedReceiver = ReadonlyRef + 2,
/// <summary>
/// Expression is passed as a ref or out parameter or assigned to a byref variable.
/// </summary>
RefOrOut = RefersToLocation | RValue | Assignable,
/// <summary>
/// Expression is returned by an ordinary r/w reference.
/// Same as RefOrOut. The difference is just for error reporting.
/// </summary>
RefReturn = RefOrOut + 1,
}
private static bool RequiresRValueOnly(BindValueKind kind)
{
return (kind & ValueKindSignificantBitsMask) == BindValueKind.RValue;
}
private static bool RequiresAssignmentOnly(BindValueKind kind)
{
return (kind & ValueKindSignificantBitsMask) == BindValueKind.Assignable;
}
private static bool RequiresVariable(BindValueKind kind)
{
return !RequiresRValueOnly(kind);
}
private static bool RequiresReferenceToLocation(BindValueKind kind)
{
return (kind & BindValueKind.RefersToLocation) != 0;
}
private static bool RequiresAssignableVariable(BindValueKind kind)
{
return (kind & BindValueKind.Assignable) != 0;
}
private static bool RequiresRefAssignableVariable(BindValueKind kind)
{
return (kind & BindValueKind.RefAssignable) != 0;
}
private static bool RequiresRefOrOut(BindValueKind kind)
{
return (kind & BindValueKind.RefOrOut) == BindValueKind.RefOrOut;
}
#nullable enable
private BoundIndexerAccess BindIndexerDefaultArguments(BoundIndexerAccess indexerAccess, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
var useSetAccessor = valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef;
var accessorForDefaultArguments = useSetAccessor
? indexerAccess.Indexer.GetOwnOrInheritedSetMethod()
: indexerAccess.Indexer.GetOwnOrInheritedGetMethod();
if (accessorForDefaultArguments is not null)
{
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(accessorForDefaultArguments.ParameterCount);
argumentsBuilder.AddRange(indexerAccess.Arguments);
ArrayBuilder<RefKind>? refKindsBuilderOpt;
if (!indexerAccess.ArgumentRefKindsOpt.IsDefaultOrEmpty)
{
refKindsBuilderOpt = ArrayBuilder<RefKind>.GetInstance(accessorForDefaultArguments.ParameterCount);
refKindsBuilderOpt.AddRange(indexerAccess.ArgumentRefKindsOpt);
}
else
{
refKindsBuilderOpt = null;
}
var argsToParams = indexerAccess.ArgsToParamsOpt;
// It is possible for the indexer 'value' parameter from metadata to have a default value, but the compiler will not use it.
// However, we may still use any default values from the preceding parameters.
var parameters = accessorForDefaultArguments.Parameters;
if (useSetAccessor)
{
parameters = parameters.RemoveAt(parameters.Length - 1);
}
BitVector defaultArguments = default;
Debug.Assert(parameters.Length == indexerAccess.Indexer.Parameters.Length);
// If OriginalIndexersOpt is set, there was an overload resolution failure, and we don't want to make guesses about the default
// arguments that will end up being reflected in the SemanticModel/IOperation
if (indexerAccess.OriginalIndexersOpt.IsDefault)
{
BindDefaultArguments(indexerAccess.Syntax, parameters, argumentsBuilder, refKindsBuilderOpt, ref argsToParams, out defaultArguments, indexerAccess.Expanded, enableCallerInfo: true, diagnostics);
}
indexerAccess = indexerAccess.Update(
indexerAccess.ReceiverOpt,
indexerAccess.Indexer,
argumentsBuilder.ToImmutableAndFree(),
indexerAccess.ArgumentNamesOpt,
refKindsBuilderOpt?.ToImmutableOrNull() ?? default,
indexerAccess.Expanded,
argsToParams,
defaultArguments,
indexerAccess.Type);
refKindsBuilderOpt?.Free();
}
return indexerAccess;
}
#nullable disable
/// <summary>
/// Check the expression is of the required lvalue and rvalue specified by valueKind.
/// The method returns the original expression if the expression is of the required
/// type. Otherwise, an appropriate error is added to the diagnostics bag and the
/// method returns a BoundBadExpression node. The method returns the original
/// expression without generating any error if the expression has errors.
/// </summary>
private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
switch (expr.Kind)
{
case BoundKind.PropertyGroup:
expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics);
if (expr is BoundIndexerAccess indexerAccess)
{
expr = BindIndexerDefaultArguments(indexerAccess, valueKind, diagnostics);
}
break;
case BoundKind.Local:
Debug.Assert(expr.Syntax.Kind() != SyntaxKind.Argument || valueKind == BindValueKind.RefOrOut);
break;
case BoundKind.OutVariablePendingInference:
case BoundKind.OutDeconstructVarPendingInference:
Debug.Assert(valueKind == BindValueKind.RefOrOut);
return expr;
case BoundKind.DiscardExpression:
Debug.Assert(valueKind == BindValueKind.Assignable || valueKind == BindValueKind.RefOrOut || diagnostics.DiagnosticBag is null || diagnostics.HasAnyResolvedErrors());
return expr;
case BoundKind.IndexerAccess:
expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics);
break;
case BoundKind.UnconvertedObjectCreationExpression:
if (valueKind == BindValueKind.RValue)
{
return expr;
}
break;
}
bool hasResolutionErrors = false;
// If this a MethodGroup where an rvalue is not expected or where the caller will not explicitly handle
// (and resolve) MethodGroups (in short, cases where valueKind != BindValueKind.RValueOrMethodGroup),
// resolve the MethodGroup here to generate the appropriate errors, otherwise resolution errors (such as
// "member is inaccessible") will be dropped.
if (expr.Kind == BoundKind.MethodGroup && valueKind != BindValueKind.RValueOrMethodGroup)
{
var methodGroup = (BoundMethodGroup)expr;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo);
diagnostics.Add(expr.Syntax, useSiteInfo);
Symbol otherSymbol = null;
bool resolvedToMethodGroup = resolution.MethodGroup != null;
if (!expr.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading.
hasResolutionErrors = resolution.HasAnyErrors;
if (hasResolutionErrors)
{
otherSymbol = resolution.OtherSymbol;
}
resolution.Free();
// It's possible the method group is not a method group at all, but simply a
// delayed lookup that resolved to a non-method member (perhaps an inaccessible
// field or property), or nothing at all. In those cases, the member should not be exposed as a
// method group, not even within a BoundBadExpression. Instead, the
// BoundBadExpression simply refers to the receiver and the resolved symbol (if any).
if (!resolvedToMethodGroup)
{
Debug.Assert(methodGroup.ResultKind != LookupResultKind.Viable);
var receiver = methodGroup.ReceiverOpt;
if ((object)otherSymbol != null && receiver?.Kind == BoundKind.TypeOrValueExpression)
{
// Since we're not accessing a method, this can't be a Color Color case, so TypeOrValueExpression should not have been used.
// CAVEAT: otherSymbol could be invalid in some way (e.g. inaccessible), in which case we would have fallen back on a
// method group lookup (to allow for extension methods), which would have required a TypeOrValueExpression.
Debug.Assert(methodGroup.LookupError != null);
// Since we have a concrete member in hand, we can resolve the receiver.
var typeOrValue = (BoundTypeOrValueExpression)receiver;
receiver = otherSymbol.RequiresInstanceReceiver()
? typeOrValue.Data.ValueExpression
: null; // no receiver required
}
return new BoundBadExpression(
expr.Syntax,
methodGroup.ResultKind,
(object)otherSymbol == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(otherSymbol),
receiver == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(receiver),
GetNonMethodMemberType(otherSymbol));
}
}
if (!hasResolutionErrors && CheckValueKind(expr.Syntax, expr, valueKind, checkingReceiver: false, diagnostics: diagnostics) ||
expr.HasAnyErrors && valueKind == BindValueKind.RValueOrMethodGroup)
{
return expr;
}
var resultKind = (valueKind == BindValueKind.RValue || valueKind == BindValueKind.RValueOrMethodGroup) ?
LookupResultKind.NotAValue :
LookupResultKind.NotAVariable;
return ToBadExpression(expr, resultKind);
}
internal static bool IsTypeOrValueExpression(BoundExpression expression)
{
switch (expression?.Kind)
{
case BoundKind.TypeOrValueExpression:
case BoundKind.QueryClause when ((BoundQueryClause)expression).Value.Kind == BoundKind.TypeOrValueExpression:
return true;
default:
return false;
}
}
/// <summary>
/// The purpose of this method is to determine if the expression satisfies desired capabilities.
/// If it is not then this code gives an appropriate error message.
///
/// To determine the appropriate error message we need to know two things:
///
/// (1) What capabilities we need - increment it, assign, return as a readonly reference, . . . ?
///
/// (2) Are we trying to determine if the left hand side of a dot is a variable in order
/// to determine if the field or property on the right hand side of a dot is assignable?
///
/// (3) The syntax of the expression that started the analysis. (for error reporting purposes).
/// </summary>
internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter());
if (expr.HasAnyErrors)
{
return false;
}
switch (expr.Kind)
{
// we need to handle properties and event in a special way even in an RValue case because of getters
case BoundKind.PropertyAccess:
case BoundKind.IndexerAccess:
return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = ((BoundIndexOrRangePatternIndexerAccess)expr);
if (patternIndexer.PatternSymbol.Kind == SymbolKind.Property)
{
// If this is an Index indexer, PatternSymbol should be a property, pointing to the
// pattern indexer. If it's a Range access, it will be a method, pointing to a Slice method
// and it's handled below as part of invocations.
return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics);
}
Debug.Assert(patternIndexer.PatternSymbol.Kind == SymbolKind.Method);
break;
case BoundKind.EventAccess:
return CheckEventValueKind((BoundEventAccess)expr, valueKind, diagnostics);
}
// easy out for a very common RValue case.
if (RequiresRValueOnly(valueKind))
{
return CheckNotNamespaceOrType(expr, diagnostics);
}
// constants/literals are strictly RValues
// void is not even an RValue
if ((expr.ConstantValue != null) || (expr.Type.GetSpecialTypeSafe() == SpecialType.System_Void))
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
switch (expr.Kind)
{
case BoundKind.NamespaceExpression:
var ns = (BoundNamespaceExpression)expr;
Error(diagnostics, ErrorCode.ERR_BadSKknown, node, ns.NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.TypeExpression:
var type = (BoundTypeExpression)expr;
Error(diagnostics, ErrorCode.ERR_BadSKknown, node, type.Type, MessageID.IDS_SK_TYPE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.Lambda:
case BoundKind.UnboundLambda:
// lambdas can only be used as RValues
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
case BoundKind.UnconvertedAddressOfOperator:
var unconvertedAddressOf = (BoundUnconvertedAddressOfOperator)expr;
Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, unconvertedAddressOf.Operand.Name, MessageID.IDS_AddressOfMethodGroup.Localize());
return false;
case BoundKind.MethodGroup when valueKind == BindValueKind.AddressOf:
// If the addressof operator is used not as an rvalue, that will get flagged when CheckValue
// is called on the parent BoundUnconvertedAddressOf node.
return true;
case BoundKind.MethodGroup:
// method groups can only be used as RValues except when taking the address of one
var methodGroup = (BoundMethodGroup)expr;
Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, methodGroup.Name, MessageID.IDS_MethodGroup.Localize());
return false;
case BoundKind.RangeVariable:
// range variables can only be used as RValues
var queryref = (BoundRangeVariable)expr;
Error(diagnostics, GetRangeLvalueError(valueKind), node, queryref.RangeVariableSymbol.Name);
return false;
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
// conversions are strict RValues, but unboxing has a specific error
if (conversion.ConversionKind == ConversionKind.Unboxing)
{
Error(diagnostics, ErrorCode.ERR_UnboxNotLValue, node);
return false;
}
break;
// array access is readwrite variable if the indexing expression is not System.Range
case BoundKind.ArrayAccess:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
var boundAccess = (BoundArrayAccess)expr;
if (boundAccess.Indices.Length == 1 &&
TypeSymbol.Equals(
boundAccess.Indices[0].Type,
Compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything))
{
// Range indexer is an rvalue
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
return true;
}
// pointer dereferencing is a readwrite variable
case BoundKind.PointerIndirectionOperator:
// The undocumented __refvalue(tr, T) expression results in a variable of type T.
case BoundKind.RefValueOperator:
// dynamic expressions are readwrite, and can even be passed by ref (which is implemented via a temp)
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// These are readwrite variables
return true;
}
case BoundKind.PointerElementAccess:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
var receiver = ((BoundPointerElementAccess)expr).Expression;
if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer)
{
return CheckValueKind(node, fieldAccess.ReceiverOpt, valueKind, checkingReceiver: true, diagnostics);
}
return true;
}
case BoundKind.Parameter:
var parameter = (BoundParameter)expr;
return CheckParameterValueKind(node, parameter, valueKind, checkingReceiver, diagnostics);
case BoundKind.Local:
var local = (BoundLocal)expr;
return CheckLocalValueKind(node, local, valueKind, checkingReceiver, diagnostics);
case BoundKind.ThisReference:
// `this` is never ref assignable
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// We will already have given an error for "this" used outside of a constructor,
// instance method, or instance accessor. Assume that "this" is a variable if it is in a struct.
// SPEC: when this is used in a primary-expression within an instance constructor of a struct,
// SPEC: it is classified as a variable.
// SPEC: When this is used in a primary-expression within an instance method or instance accessor
// SPEC: of a struct, it is classified as a variable.
// Note: RValueOnly is checked at the beginning of this method. Since we are here we need more than readable.
// "this" is readonly in members marked "readonly" and in members of readonly structs, unless we are in a constructor.
var isValueType = ((BoundThisReference)expr).Type.IsValueType;
if (!isValueType || (RequiresAssignableVariable(valueKind) && (this.ContainingMemberOrLambda as MethodSymbol)?.IsEffectivelyReadOnly == true))
{
Error(diagnostics, GetThisLvalueError(valueKind, isValueType), node, node);
return false;
}
return true;
case BoundKind.ImplicitReceiver:
case BoundKind.ObjectOrCollectionValuePlaceholder:
Debug.Assert(!RequiresRefAssignableVariable(valueKind));
return true;
case BoundKind.Call:
var call = (BoundCall)expr;
return CheckCallValueKind(call, node, valueKind, checkingReceiver, diagnostics);
case BoundKind.FunctionPointerInvocation:
return CheckMethodReturnValueKind(((BoundFunctionPointerInvocation)expr).FunctionPointer.Signature,
expr.Syntax,
node,
valueKind,
checkingReceiver,
diagnostics);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
// If we got here this should be a pattern indexer taking a Range,
// meaning that the pattern symbol must be a method (either Slice or Substring)
return CheckMethodReturnValueKind(
(MethodSymbol)patternIndexer.PatternSymbol,
patternIndexer.Syntax,
node,
valueKind,
checkingReceiver,
diagnostics);
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
// byref conditional defers to its operands
if (conditional.IsRef &&
(CheckValueKind(conditional.Consequence.Syntax, conditional.Consequence, valueKind, checkingReceiver: false, diagnostics: diagnostics) &
CheckValueKind(conditional.Alternative.Syntax, conditional.Alternative, valueKind, checkingReceiver: false, diagnostics: diagnostics)))
{
return true;
}
// report standard lvalue error
break;
case BoundKind.FieldAccess:
{
var fieldAccess = (BoundFieldAccess)expr;
return CheckFieldValueKind(node, fieldAccess, valueKind, checkingReceiver, diagnostics);
}
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
return CheckSimpleAssignmentValueKind(node, assignment, valueKind, diagnostics);
}
// At this point we should have covered all the possible cases for anything that is not a strict RValue.
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
private static bool CheckNotNamespaceOrType(BoundExpression expr, BindingDiagnosticBag diagnostics)
{
switch (expr.Kind)
{
case BoundKind.NamespaceExpression:
Error(diagnostics, ErrorCode.ERR_BadSKknown, expr.Syntax, ((BoundNamespaceExpression)expr).NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.TypeExpression:
Error(diagnostics, ErrorCode.ERR_BadSKunknown, expr.Syntax, expr.Type, MessageID.IDS_SK_TYPE.Localize());
return false;
default:
return true;
}
}
private bool CheckLocalValueKind(SyntaxNode node, BoundLocal local, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
// Local constants are never variables. Local variables are sometimes
// not to be treated as variables, if they are fixed, declared in a using,
// or declared in a foreach.
LocalSymbol localSymbol = local.LocalSymbol;
if (RequiresAssignableVariable(valueKind))
{
if (this.LockedOrDisposedVariables.Contains(localSymbol))
{
diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, local.Syntax.Location, localSymbol);
}
// IsWritable means the variable is writable. If this is a ref variable, IsWritable
// does not imply anything about the storage location
if (localSymbol.RefKind == RefKind.RefReadOnly ||
(localSymbol.RefKind == RefKind.None && !localSymbol.IsWritableVariable))
{
ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics);
return false;
}
}
else if (RequiresRefAssignableVariable(valueKind))
{
if (localSymbol.RefKind == RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_RefLocalOrParamExpected, node.Location, localSymbol);
return false;
}
else if (!localSymbol.IsWritableVariable)
{
ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics);
return false;
}
}
return true;
}
private static bool CheckLocalRefEscape(SyntaxNode node, BoundLocal local, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
LocalSymbol localSymbol = local.LocalSymbol;
// if local symbol can escape to the same or wider/shallower scope then escapeTo
// then it is all ok, otherwise it is an error.
if (localSymbol.RefEscapeScope <= escapeTo)
{
return true;
}
if (escapeTo == Binder.ExternalScope)
{
if (localSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnLocal, node, localSymbol);
}
return false;
}
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal, node, localSymbol);
}
return false;
}
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol);
return false;
}
private bool CheckParameterValueKind(SyntaxNode node, BoundParameter parameter, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
ParameterSymbol parameterSymbol = parameter.ParameterSymbol;
// all parameters can be passed by ref/out or assigned to
// except "in" parameters, which are readonly
if (parameterSymbol.RefKind == RefKind.In && RequiresAssignableVariable(valueKind))
{
ReportReadOnlyError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
else if (parameterSymbol.RefKind == RefKind.None && RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
if (this.LockedOrDisposedVariables.Contains(parameterSymbol))
{
// Consider: It would be more conventional to pass "symbol" rather than "symbol.Name".
// The issue is that the error SymbolDisplayFormat doesn't display parameter
// names - only their types - which works great in signatures, but not at all
// at the top level.
diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, parameter.Syntax.Location, parameterSymbol.Name);
}
return true;
}
private static bool CheckParameterRefEscape(SyntaxNode node, BoundParameter parameter, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
ParameterSymbol parameterSymbol = parameter.ParameterSymbol;
// byval parameters can escape to method's top level. Others can escape further.
// NOTE: "method" here means nearest containing method, lambda or local function.
if (escapeTo == Binder.ExternalScope && parameterSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnParameter2, parameter.Syntax, parameterSymbol.Name);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnParameter, node, parameterSymbol.Name);
}
return false;
}
// can ref-escape to any scope otherwise
return true;
}
private bool CheckFieldValueKind(SyntaxNode node, BoundFieldAccess fieldAccess, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
var fieldSymbol = fieldAccess.FieldSymbol;
var fieldIsStatic = fieldSymbol.IsStatic;
if (RequiresAssignableVariable(valueKind))
{
// A field is writeable unless
// (1) it is readonly and we are not in a constructor or field initializer
// (2) the receiver of the field is of value type and is not a variable or object creation expression.
// For example, if you have a class C with readonly field f of type S, and
// S has a mutable field x, then c.f.x is not a variable because c.f is not
// writable.
if (fieldSymbol.IsReadOnly)
{
var canModifyReadonly = false;
Symbol containing = this.ContainingMemberOrLambda;
if ((object)containing != null &&
fieldIsStatic == containing.IsStatic &&
(fieldIsStatic || fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference) &&
(Compilation.FeatureStrictEnabled
? TypeSymbol.Equals(fieldSymbol.ContainingType, containing.ContainingType, TypeCompareKind.ConsiderEverything2)
// We duplicate a bug in the native compiler for compatibility in non-strict mode
: TypeSymbol.Equals(fieldSymbol.ContainingType.OriginalDefinition, containing.ContainingType.OriginalDefinition, TypeCompareKind.ConsiderEverything2)))
{
if (containing.Kind == SymbolKind.Method)
{
MethodSymbol containingMethod = (MethodSymbol)containing;
MethodKind desiredMethodKind = fieldIsStatic ? MethodKind.StaticConstructor : MethodKind.Constructor;
canModifyReadonly = (containingMethod.MethodKind == desiredMethodKind) ||
isAssignedFromInitOnlySetterOnThis(fieldAccess.ReceiverOpt);
}
else if (containing.Kind == SymbolKind.Field)
{
canModifyReadonly = true;
}
}
if (!canModifyReadonly)
{
ReportReadOnlyFieldError(fieldSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
}
if (fieldSymbol.IsFixedSizeBuffer)
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
}
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// r/w fields that are static or belong to reference types are writeable and returnable
if (fieldIsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other fields defer to the receiver.
return CheckIsValidReceiverForVariable(node, fieldAccess.ReceiverOpt, valueKind, diagnostics);
bool isAssignedFromInitOnlySetterOnThis(BoundExpression receiver)
{
// bad: other.readonlyField = ...
// bad: base.readonlyField = ...
if (!(receiver is BoundThisReference))
{
return false;
}
if (!(ContainingMemberOrLambda is MethodSymbol method))
{
return false;
}
return method.IsInitOnly;
}
}
private bool CheckSimpleAssignmentValueKind(SyntaxNode node, BoundAssignmentOperator assignment, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
// Only ref-assigns produce LValues
if (assignment.IsRef)
{
return CheckValueKind(node, assignment.Left, valueKind, checkingReceiver: false, diagnostics);
}
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
private static bool CheckFieldRefEscape(SyntaxNode node, BoundFieldAccess fieldAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
var fieldSymbol = fieldAccess.FieldSymbol;
// fields that are static or belong to reference types can ref escape anywhere
if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other fields defer to the receiver.
return CheckRefEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics);
}
private static bool CheckFieldLikeEventRefEscape(SyntaxNode node, BoundEventAccess eventAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
var eventSymbol = eventAccess.EventSymbol;
// field-like events that are static or belong to reference types can ref escape anywhere
if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other events defer to the receiver.
return CheckRefEscape(node, eventAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics);
}
private bool CheckEventValueKind(BoundEventAccess boundEvent, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
// Compound assignment (actually "event assignment") is allowed "everywhere", subject to the restrictions of
// accessibility, use site errors, and receiver variable-ness (for structs).
// Other operations are allowed only for field-like events and only where the backing field is accessible
// (i.e. in the declaring type) - subject to use site errors and receiver variable-ness.
BoundExpression receiver = boundEvent.ReceiverOpt;
SyntaxNode eventSyntax = GetEventName(boundEvent); //does not include receiver
EventSymbol eventSymbol = boundEvent.EventSymbol;
if (valueKind == BindValueKind.CompoundAssignment)
{
// NOTE: accessibility has already been checked by lookup.
// NOTE: availability of well-known members is checked in BindEventAssignment because
// we don't have the context to determine whether addition or subtraction is being performed.
if (ReportUseSite(eventSymbol, diagnostics, eventSyntax))
{
// NOTE: BindEventAssignment checks use site errors on the specific accessor
// (since we don't know which is being used).
return false;
}
Debug.Assert(!RequiresVariableReceiver(receiver, eventSymbol));
return true;
}
else
{
if (!boundEvent.IsUsableAsField)
{
// Dev10 reports this in addition to ERR_BadAccess, but we won't even reach this point if the event isn't accessible (caught by lookup).
Error(diagnostics, GetBadEventUsageDiagnosticInfo(eventSymbol), eventSyntax);
return false;
}
else if (ReportUseSite(eventSymbol, diagnostics, eventSyntax))
{
if (!CheckIsValidReceiverForVariable(eventSyntax, receiver, BindValueKind.Assignable, diagnostics))
{
return false;
}
}
else if (RequiresVariable(valueKind))
{
if (eventSymbol.IsWindowsRuntimeEvent && valueKind != BindValueKind.Assignable)
{
// NOTE: Dev11 reports ERR_RefProperty, as if this were a property access (since that's how it will be lowered).
// Roslyn reports a new, more specific, error code.
ErrorCode errorCode = valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_WinRtEventPassedByRef : GetStandardLvalueError(valueKind);
Error(diagnostics, errorCode, eventSyntax, eventSymbol);
return false;
}
else if (RequiresVariableReceiver(receiver, eventSymbol.AssociatedField) && // NOTE: using field, not event
!CheckIsValidReceiverForVariable(eventSyntax, receiver, valueKind, diagnostics))
{
return false;
}
}
return true;
}
}
private bool CheckIsValidReceiverForVariable(SyntaxNode node, BoundExpression receiver, BindValueKind kind, BindingDiagnosticBag diagnostics)
{
Debug.Assert(receiver != null);
return Flags.Includes(BinderFlags.ObjectInitializerMember) && receiver.Kind == BoundKind.ObjectOrCollectionValuePlaceholder ||
CheckValueKind(node, receiver, kind, true, diagnostics);
}
/// <summary>
/// SPEC: When a property or indexer declared in a struct-type is the target of an
/// SPEC: assignment, the instance expression associated with the property or indexer
/// SPEC: access must be classified as a variable. If the instance expression is
/// SPEC: classified as a value, a compile-time error occurs. Because of 7.6.4,
/// SPEC: the same rule also applies to fields.
/// </summary>
/// <remarks>
/// NOTE: The spec fails to impose the restriction that the event receiver must be classified
/// as a variable (unlike for properties - 7.17.1). This seems like a bug, but we have
/// production code that won't build with the restriction in place (see DevDiv #15674).
/// </remarks>
private static bool RequiresVariableReceiver(BoundExpression receiver, Symbol symbol)
{
return symbol.RequiresInstanceReceiver()
&& symbol.Kind != SymbolKind.Event
&& receiver?.Type?.IsValueType == true;
}
private bool CheckCallValueKind(BoundCall call, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
=> CheckMethodReturnValueKind(call.Method, call.Syntax, node, valueKind, checkingReceiver, diagnostics);
protected bool CheckMethodReturnValueKind(
MethodSymbol methodSymbol,
SyntaxNode callSyntaxOpt,
SyntaxNode node,
BindValueKind valueKind,
bool checkingReceiver,
BindingDiagnosticBag diagnostics)
{
// A call can only be a variable if it returns by reference. If this is the case,
// whether or not it is a valid variable depends on whether or not the call is the
// RHS of a return or an assign by reference:
// - If call is used in a context demanding ref-returnable reference all of its ref
// inputs must be ref-returnable
if (RequiresVariable(valueKind) && methodSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
// Error is associated with expression, not node which may be distinct.
Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, callSyntaxOpt, methodSymbol);
}
else
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
}
return false;
}
if (RequiresAssignableVariable(valueKind) && methodSymbol.RefKind == RefKind.RefReadOnly)
{
ReportReadOnlyError(methodSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
return true;
}
private bool CheckPropertyValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
// SPEC: If the left operand is a property or indexer access, the property or indexer must
// SPEC: have a set accessor. If this is not the case, a compile-time error occurs.
// Addendum: Assignment is also allowed for get-only autoprops in their constructor
BoundExpression receiver;
SyntaxNode propertySyntax;
var propertySymbol = GetPropertySymbol(expr, out receiver, out propertySyntax);
Debug.Assert((object)propertySymbol != null);
Debug.Assert(propertySyntax != null);
if ((RequiresReferenceToLocation(valueKind) || checkingReceiver) &&
propertySymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
// Error is associated with expression, not node which may be distinct.
// This error is reported for all values types. That is a breaking
// change from Dev10 which reports this error for struct types only,
// not for type parameters constrained to "struct".
Debug.Assert(propertySymbol.TypeWithAnnotations.HasType);
Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, expr.Syntax, propertySymbol);
}
else
{
Error(diagnostics, valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_RefProperty : GetStandardLvalueError(valueKind), node, propertySymbol);
}
return false;
}
if (RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.RefReadOnly)
{
ReportReadOnlyError(propertySymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
var requiresSet = RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.None;
if (requiresSet)
{
var setMethod = propertySymbol.GetOwnOrInheritedSetMethod();
if (setMethod is null)
{
var containing = this.ContainingMemberOrLambda;
if (!AccessingAutoPropertyFromConstructor(receiver, propertySymbol, containing)
&& !isAllowedDespiteReadonly(receiver))
{
Error(diagnostics, ErrorCode.ERR_AssgReadonlyProp, node, propertySymbol);
return false;
}
}
else
{
if (setMethod.IsInitOnly)
{
if (!isAllowedInitOnlySet(receiver))
{
Error(diagnostics, ErrorCode.ERR_AssignmentInitOnly, node, propertySymbol);
return false;
}
if (setMethod.DeclaringCompilation != this.Compilation)
{
// an error would have already been reported on declaring an init-only setter
CheckFeatureAvailability(node, MessageID.IDS_FeatureInitOnlySetters, diagnostics);
}
}
var accessThroughType = this.GetAccessThroughType(receiver);
bool failedThroughTypeCheck;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
bool isAccessible = this.IsAccessible(setMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!isAccessible)
{
if (failedThroughTypeCheck)
{
Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType);
}
else
{
Error(diagnostics, ErrorCode.ERR_InaccessibleSetter, node, propertySymbol);
}
return false;
}
ReportDiagnosticsIfObsolete(diagnostics, setMethod, node, receiver?.Kind == BoundKind.BaseReference);
var setValueKind = setMethod.IsEffectivelyReadOnly ? BindValueKind.RValue : BindValueKind.Assignable;
if (RequiresVariableReceiver(receiver, setMethod) && !CheckIsValidReceiverForVariable(node, receiver, setValueKind, diagnostics))
{
return false;
}
if (IsBadBaseAccess(node, receiver, setMethod, diagnostics, propertySymbol) ||
reportUseSite(setMethod))
{
return false;
}
CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, setMethod, diagnostics);
}
}
var requiresGet = !RequiresAssignmentOnly(valueKind) || propertySymbol.RefKind != RefKind.None;
if (requiresGet)
{
var getMethod = propertySymbol.GetOwnOrInheritedGetMethod();
if ((object)getMethod == null)
{
Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, node, propertySymbol);
return false;
}
else
{
var accessThroughType = this.GetAccessThroughType(receiver);
bool failedThroughTypeCheck;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
bool isAccessible = this.IsAccessible(getMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!isAccessible)
{
if (failedThroughTypeCheck)
{
Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType);
}
else
{
Error(diagnostics, ErrorCode.ERR_InaccessibleGetter, node, propertySymbol);
}
return false;
}
CheckImplicitThisCopyInReadOnlyMember(receiver, getMethod, diagnostics);
ReportDiagnosticsIfObsolete(diagnostics, getMethod, node, receiver?.Kind == BoundKind.BaseReference);
if (IsBadBaseAccess(node, receiver, getMethod, diagnostics, propertySymbol) ||
reportUseSite(getMethod))
{
return false;
}
CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, getMethod, diagnostics);
}
}
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
return true;
bool reportUseSite(MethodSymbol accessor)
{
UseSiteInfo<AssemblySymbol> useSiteInfo = accessor.GetUseSiteInfo();
if (!object.Equals(useSiteInfo.DiagnosticInfo, propertySymbol.GetUseSiteInfo().DiagnosticInfo))
{
return diagnostics.Add(useSiteInfo, propertySyntax);
}
else
{
diagnostics.AddDependencies(useSiteInfo);
}
return false;
}
static bool isAllowedDespiteReadonly(BoundExpression receiver)
{
// ok: anonymousType with { Property = ... }
if (receiver is BoundObjectOrCollectionValuePlaceholder && receiver.Type.IsAnonymousType)
{
return true;
}
return false;
}
bool isAllowedInitOnlySet(BoundExpression receiver)
{
// ok: new C() { InitOnlyProperty = ... }
// bad: { ... = { InitOnlyProperty = ... } }
if (receiver is BoundObjectOrCollectionValuePlaceholder placeholder)
{
return placeholder.IsNewInstance;
}
// bad: other.InitOnlyProperty = ...
if (!(receiver is BoundThisReference || receiver is BoundBaseReference))
{
return false;
}
var containingMember = ContainingMemberOrLambda;
if (!(containingMember is MethodSymbol method))
{
return false;
}
if (method.MethodKind == MethodKind.Constructor || method.IsInitOnly)
{
// ok: setting on `this` or `base` from an instance constructor or init-only setter
return true;
}
return false;
}
}
private bool IsBadBaseAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol member, BindingDiagnosticBag diagnostics,
Symbol propertyOrEventSymbolOpt = null)
{
Debug.Assert(member.Kind != SymbolKind.Property);
Debug.Assert(member.Kind != SymbolKind.Event);
if (receiverOpt?.Kind == BoundKind.BaseReference && member.IsAbstract)
{
Error(diagnostics, ErrorCode.ERR_AbstractBaseCall, node, propertyOrEventSymbolOpt ?? member);
return true;
}
return false;
}
internal static uint GetInterpolatedStringHandlerConversionEscapeScope(
BoundInterpolatedString interpolatedString,
uint scopeOfTheContainingExpression)
{
Debug.Assert(interpolatedString.InterpolationData != null);
var data = interpolatedString.InterpolationData.GetValueOrDefault();
return GetValEscape(data.Construction, scopeOfTheContainingExpression);
}
/// <summary>
/// Computes the scope to which the given invocation can escape
/// NOTE: the escape scope for ref and val escapes is the same for invocations except for trivial cases (ordinary type returned by val)
/// where escape is known otherwise. Therefore we do not vave two ref/val variants of this.
///
/// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as
/// local variables declared at the scope of the invocation.
/// </summary>
internal static uint GetInvocationEscapeScope(
Symbol symbol,
BoundExpression receiverOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<BoundExpression> argsOpt,
ImmutableArray<RefKind> argRefKindsOpt,
ImmutableArray<int> argsToParamsOpt,
uint scopeOfTheContainingExpression,
bool isRefEscape
)
{
// SPEC: (also applies to the CheckInvocationEscape counterpart)
//
// An lvalue resulting from a ref-returning method invocation e1.M(e2, ...) is ref-safe - to - escape the smallest of the following scopes:
//• The entire enclosing method
//• the ref-safe-to-escape of all ref/out/in argument expressions(excluding the receiver)
//• the safe-to - escape of all argument expressions(including the receiver)
//
// An rvalue resulting from a method invocation e1.M(e2, ...) is safe - to - escape from the smallest of the following scopes:
//• The entire enclosing method
//• the safe-to-escape of all argument expressions(including the receiver)
//
if (!symbol.RequiresInstanceReceiver())
{
// ignore receiver when symbol is static
receiverOpt = null;
}
//by default it is safe to escape
uint escapeScope = Binder.ExternalScope;
ArrayBuilder<bool> inParametersMatchedWithArgs = null;
if (!argsOpt.IsDefault)
{
moreArguments:
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
var argList = (BoundArgListOperator)argument;
// unwrap varargs and process as more arguments
argsOpt = argList.Arguments;
// ref kinds of varargs are not interesting here.
// __refvalue is not ref-returnable, so ref varargs can't come back from a call
argRefKindsOpt = default;
parameters = ImmutableArray<ParameterSymbol>.Empty;
argsToParamsOpt = default;
goto moreArguments;
}
RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs);
// ref escape scope is the narrowest of
// - ref escape of all byref arguments
// - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result)
//
// val escape scope is the narrowest of
// - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes)
var argEscape = effectiveRefKind != RefKind.None && isRefEscape ?
GetRefEscape(argument, scopeOfTheContainingExpression) :
GetValEscape(argument, scopeOfTheContainingExpression);
escapeScope = Math.Max(escapeScope, argEscape);
if (escapeScope >= scopeOfTheContainingExpression)
{
// no longer needed
inParametersMatchedWithArgs?.Free();
// can't get any worse
return escapeScope;
}
}
}
// handle omitted optional "in" parameters if there are any
ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs);
// unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse)
// its val escape is ExternalScope (does not affect overall result)
if (unmatchedInParameter != null && isRefEscape)
{
return scopeOfTheContainingExpression;
}
// check receiver if ref-like
if (receiverOpt?.Type?.IsRefLikeType == true)
{
escapeScope = Math.Max(escapeScope, GetValEscape(receiverOpt, scopeOfTheContainingExpression));
}
return escapeScope;
}
/// <summary>
/// Validates whether given invocation can allow its results to escape from <paramref name="escapeFrom"/> level to <paramref name="escapeTo"/> level.
/// The result indicates whether the escape is possible.
/// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure.
///
/// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as
/// local variables declared at the scope of the invocation.
/// </summary>
private static bool CheckInvocationEscape(
SyntaxNode syntax,
Symbol symbol,
BoundExpression receiverOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<BoundExpression> argsOpt,
ImmutableArray<RefKind> argRefKindsOpt,
ImmutableArray<int> argsToParamsOpt,
bool checkingReceiver,
uint escapeFrom,
uint escapeTo,
BindingDiagnosticBag diagnostics,
bool isRefEscape
)
{
// SPEC:
// In a method invocation, the following constraints apply:
//• If there is a ref or out argument to a ref struct type (including the receiver), with safe-to-escape E1, then
// o no ref or out argument(excluding the receiver and arguments of ref-like types) may have a narrower ref-safe-to-escape than E1; and
// o no argument(including the receiver) may have a narrower safe-to-escape than E1.
if (!symbol.RequiresInstanceReceiver())
{
// ignore receiver when symbol is static
receiverOpt = null;
}
ArrayBuilder<bool> inParametersMatchedWithArgs = null;
if (!argsOpt.IsDefault)
{
moreArguments:
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
var argList = (BoundArgListOperator)argument;
// unwrap varargs and process as more arguments
argsOpt = argList.Arguments;
// ref kinds of varargs are not interesting here.
// __refvalue is not ref-returnable, so ref varargs can't come back from a call
argRefKindsOpt = default;
parameters = ImmutableArray<ParameterSymbol>.Empty;
argsToParamsOpt = default;
goto moreArguments;
}
RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs);
// ref escape scope is the narrowest of
// - ref escape of all byref arguments
// - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result)
//
// val escape scope is the narrowest of
// - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes)
var valid = effectiveRefKind != RefKind.None && isRefEscape ?
CheckRefEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics) :
CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics);
if (!valid)
{
// no longer needed
inParametersMatchedWithArgs?.Free();
ErrorCode errorCode = GetStandardCallEscapeError(checkingReceiver);
string parameterName;
if (parameters.Length > 0)
{
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
parameterName = parameters[paramIndex].Name;
if (string.IsNullOrEmpty(parameterName))
{
parameterName = paramIndex.ToString();
}
}
else
{
parameterName = "__arglist";
}
Error(diagnostics, errorCode, syntax, symbol, parameterName);
return false;
}
}
}
// handle omitted optional "in" parameters if there are any
ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs);
// unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse)
// its val escape is ExternalScope (does not affect overall result)
if (unmatchedInParameter != null && isRefEscape)
{
var parameterName = unmatchedInParameter.Name;
if (string.IsNullOrEmpty(parameterName))
{
parameterName = unmatchedInParameter.Ordinal.ToString();
}
Error(diagnostics, GetStandardCallEscapeError(checkingReceiver), syntax, symbol, parameterName);
return false;
}
// check receiver if ref-like
if (receiverOpt?.Type?.IsRefLikeType == true)
{
return CheckValEscape(receiverOpt.Syntax, receiverOpt, escapeFrom, escapeTo, false, diagnostics);
}
return true;
}
/// <summary>
/// Validates whether the invocation is valid per no-mixing rules.
/// Returns <see langword="false"/> when it is not valid and produces diagnostics (possibly more than one recursively) that helps to figure the reason.
/// </summary>
private static bool CheckInvocationArgMixing(
SyntaxNode syntax,
Symbol symbol,
BoundExpression receiverOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<BoundExpression> argsOpt,
ImmutableArray<int> argsToParamsOpt,
uint scopeOfTheContainingExpression,
BindingDiagnosticBag diagnostics)
{
// SPEC:
// In a method invocation, the following constraints apply:
// - If there is a ref or out argument of a ref struct type (including the receiver), with safe-to-escape E1, then
// - no argument (including the receiver) may have a narrower safe-to-escape than E1.
if (!symbol.RequiresInstanceReceiver())
{
// ignore receiver when symbol is static
receiverOpt = null;
}
// widest possible escape via writeable ref-like receiver or ref/out argument.
uint escapeTo = scopeOfTheContainingExpression;
// collect all writeable ref-like arguments, including receiver
var receiverType = receiverOpt?.Type;
if (receiverType?.IsRefLikeType == true && !isReceiverRefReadOnly(symbol))
{
escapeTo = GetValEscape(receiverOpt, scopeOfTheContainingExpression);
}
if (!argsOpt.IsDefault)
{
BoundArgListOperator argList = null;
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
argList = (BoundArgListOperator)argument;
break;
}
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
if (parameters[paramIndex].RefKind.IsWritableReference() && argument.Type?.IsRefLikeType == true)
{
escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression));
}
}
if (argList != null)
{
var argListArgs = argList.Arguments;
var argListRefKindsOpt = argList.ArgumentRefKindsOpt;
for (var argIndex = 0; argIndex < argListArgs.Length; argIndex++)
{
var argument = argListArgs[argIndex];
var refKind = argListRefKindsOpt.IsDefault ? RefKind.None : argListRefKindsOpt[argIndex];
if (refKind.IsWritableReference() && argument.Type?.IsRefLikeType == true)
{
escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression));
}
}
}
}
if (escapeTo == scopeOfTheContainingExpression)
{
// cannot fail. common case.
return true;
}
if (!argsOpt.IsDefault)
{
moreArguments:
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
// check val escape of all arguments
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
var argList = (BoundArgListOperator)argument;
// unwrap varargs and process as more arguments
argsOpt = argList.Arguments;
parameters = ImmutableArray<ParameterSymbol>.Empty;
argsToParamsOpt = default;
goto moreArguments;
}
var valid = CheckValEscape(argument.Syntax, argument, scopeOfTheContainingExpression, escapeTo, false, diagnostics);
if (!valid)
{
string parameterName;
if (parameters.Length > 0)
{
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
parameterName = parameters[paramIndex].Name;
}
else
{
parameterName = "__arglist";
}
Error(diagnostics, ErrorCode.ERR_CallArgMixing, syntax, symbol, parameterName);
return false;
}
}
}
//NB: we do not care about unmatched "in" parameters here.
// They have "outer" val escape, so cannot be worse than escapeTo.
// check val escape of receiver if ref-like
if (receiverOpt?.Type?.IsRefLikeType == true)
{
return CheckValEscape(receiverOpt.Syntax, receiverOpt, scopeOfTheContainingExpression, escapeTo, false, diagnostics);
}
return true;
static bool isReceiverRefReadOnly(Symbol methodOrPropertySymbol) => methodOrPropertySymbol switch
{
MethodSymbol m => m.IsEffectivelyReadOnly,
// TODO: val escape checks should be skipped for property accesses when
// we can determine the only accessors being called are readonly.
// For now we are pessimistic and check escape if any accessor is non-readonly.
// Tracking in https://github.com/dotnet/roslyn/issues/35606
PropertySymbol p => p.GetMethod?.IsEffectivelyReadOnly != false && p.SetMethod?.IsEffectivelyReadOnly != false,
_ => throw ExceptionUtilities.UnexpectedValue(methodOrPropertySymbol)
};
}
/// <summary>
/// Gets "effective" ref kind of an argument.
/// If the ref kind is 'in', marks that that corresponding parameter was matched with a value
/// We need that to detect when there were optional 'in' parameters for which values were not supplied.
///
/// NOTE: Generally we know if a formal argument is passed as ref/out/in by looking at the call site.
/// However, 'in' may also be passed as an ordinary val argument so we need to take a look at corresponding parameter, if such exists.
/// There are cases like params/vararg, when a corresponding parameter may not exist, then val cannot become 'in'.
/// </summary>
private static RefKind GetEffectiveRefKindAndMarkMatchedInParameter(
int argIndex,
ImmutableArray<RefKind> argRefKindsOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<int> argsToParamsOpt,
ref ArrayBuilder<bool> inParametersMatchedWithArgs)
{
var effectiveRefKind = argRefKindsOpt.IsDefault ? RefKind.None : argRefKindsOpt[argIndex];
if ((effectiveRefKind == RefKind.None || effectiveRefKind == RefKind.In) && argIndex < parameters.Length)
{
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
if (parameters[paramIndex].RefKind == RefKind.In)
{
effectiveRefKind = RefKind.In;
inParametersMatchedWithArgs = inParametersMatchedWithArgs ?? ArrayBuilder<bool>.GetInstance(parameters.Length, fillWithValue: false);
inParametersMatchedWithArgs[paramIndex] = true;
}
}
return effectiveRefKind;
}
/// <summary>
/// Gets a "in" parameter for which there is no argument supplied, if such exists.
/// That indicates an optional "in" parameter. We treat it as an RValue passed by reference via a temporary.
/// The effective scope of such variable is the immediately containing scope.
/// </summary>
private static ParameterSymbol TryGetunmatchedInParameterAndFreeMatchedArgs(ImmutableArray<ParameterSymbol> parameters, ref ArrayBuilder<bool> inParametersMatchedWithArgs)
{
try
{
if (!parameters.IsDefault)
{
for (int i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
if (parameter.IsParams)
{
break;
}
if (parameter.RefKind == RefKind.In &&
inParametersMatchedWithArgs?[i] != true &&
parameter.Type.IsRefLikeType == false)
{
return parameter;
}
}
}
return null;
}
finally
{
inParametersMatchedWithArgs?.Free();
// make sure noone uses it after.
inParametersMatchedWithArgs = null;
}
}
private static ErrorCode GetStandardCallEscapeError(bool checkingReceiver)
{
return checkingReceiver ? ErrorCode.ERR_EscapeCall2 : ErrorCode.ERR_EscapeCall;
}
private static void ReportReadonlyLocalError(SyntaxNode node, LocalSymbol local, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)local != null);
Debug.Assert(kind != BindValueKind.RValue);
MessageID cause;
if (local.IsForEach)
{
cause = MessageID.IDS_FOREACHLOCAL;
}
else if (local.IsUsing)
{
cause = MessageID.IDS_USINGLOCAL;
}
else if (local.IsFixed)
{
cause = MessageID.IDS_FIXEDLOCAL;
}
else
{
Error(diagnostics, GetStandardLvalueError(kind), node);
return;
}
ErrorCode[] ReadOnlyLocalErrors =
{
ErrorCode.ERR_RefReadonlyLocalCause,
ErrorCode.ERR_AssgReadonlyLocalCause,
ErrorCode.ERR_RefReadonlyLocal2Cause,
ErrorCode.ERR_AssgReadonlyLocal2Cause
};
int index = (checkingReceiver ? 2 : 0) + (RequiresRefOrOut(kind) ? 0 : 1);
Error(diagnostics, ReadOnlyLocalErrors[index], node, local, cause.Localize());
}
private static ErrorCode GetThisLvalueError(BindValueKind kind, bool isValueType)
{
switch (kind)
{
case BindValueKind.CompoundAssignment:
case BindValueKind.Assignable:
return ErrorCode.ERR_AssgReadonlyLocal;
case BindValueKind.RefOrOut:
return ErrorCode.ERR_RefReadonlyLocal;
case BindValueKind.AddressOf:
return ErrorCode.ERR_InvalidAddrOp;
case BindValueKind.IncrementDecrement:
return isValueType ? ErrorCode.ERR_AssgReadonlyLocal : ErrorCode.ERR_IncrementLvalueExpected;
case BindValueKind.RefReturn:
case BindValueKind.ReadonlyRef:
return ErrorCode.ERR_RefReturnThis;
case BindValueKind.RefAssignable:
return ErrorCode.ERR_RefLocalOrParamExpected;
}
if (RequiresReferenceToLocation(kind))
{
return ErrorCode.ERR_RefLvalueExpected;
}
throw ExceptionUtilities.UnexpectedValue(kind);
}
private static ErrorCode GetRangeLvalueError(BindValueKind kind)
{
switch (kind)
{
case BindValueKind.Assignable:
case BindValueKind.CompoundAssignment:
case BindValueKind.IncrementDecrement:
return ErrorCode.ERR_QueryRangeVariableReadOnly;
case BindValueKind.AddressOf:
return ErrorCode.ERR_InvalidAddrOp;
case BindValueKind.RefReturn:
case BindValueKind.ReadonlyRef:
return ErrorCode.ERR_RefReturnRangeVariable;
case BindValueKind.RefAssignable:
return ErrorCode.ERR_RefLocalOrParamExpected;
}
if (RequiresReferenceToLocation(kind))
{
return ErrorCode.ERR_QueryOutRefRangeVariable;
}
throw ExceptionUtilities.UnexpectedValue(kind);
}
private static ErrorCode GetMethodGroupOrFunctionPointerLvalueError(BindValueKind valueKind)
{
if (RequiresReferenceToLocation(valueKind))
{
return ErrorCode.ERR_RefReadonlyLocalCause;
}
// Cannot assign to 'W' because it is a 'method group'
return ErrorCode.ERR_AssgReadonlyLocalCause;
}
private static ErrorCode GetStandardLvalueError(BindValueKind kind)
{
switch (kind)
{
case BindValueKind.CompoundAssignment:
case BindValueKind.Assignable:
return ErrorCode.ERR_AssgLvalueExpected;
case BindValueKind.AddressOf:
return ErrorCode.ERR_InvalidAddrOp;
case BindValueKind.IncrementDecrement:
return ErrorCode.ERR_IncrementLvalueExpected;
case BindValueKind.FixedReceiver:
return ErrorCode.ERR_FixedNeedsLvalue;
case BindValueKind.RefReturn:
case BindValueKind.ReadonlyRef:
return ErrorCode.ERR_RefReturnLvalueExpected;
case BindValueKind.RefAssignable:
return ErrorCode.ERR_RefLocalOrParamExpected;
}
if (RequiresReferenceToLocation(kind))
{
return ErrorCode.ERR_RefLvalueExpected;
}
throw ExceptionUtilities.UnexpectedValue(kind);
}
private static ErrorCode GetStandardRValueRefEscapeError(uint escapeTo)
{
if (escapeTo == Binder.ExternalScope)
{
return ErrorCode.ERR_RefReturnLvalueExpected;
}
return ErrorCode.ERR_EscapeOther;
}
private static void ReportReadOnlyFieldError(FieldSymbol field, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)field != null);
Debug.Assert(RequiresAssignableVariable(kind));
Debug.Assert(field.Type != (object)null);
// It's clearer to say that the address can't be taken than to say that the field can't be modified
// (even though the latter message gives more explanation of why).
if (kind == BindValueKind.AddressOf)
{
Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node);
return;
}
ErrorCode[] ReadOnlyErrors =
{
ErrorCode.ERR_RefReturnReadonly,
ErrorCode.ERR_RefReadonly,
ErrorCode.ERR_AssgReadonly,
ErrorCode.ERR_RefReturnReadonlyStatic,
ErrorCode.ERR_RefReadonlyStatic,
ErrorCode.ERR_AssgReadonlyStatic,
ErrorCode.ERR_RefReturnReadonly2,
ErrorCode.ERR_RefReadonly2,
ErrorCode.ERR_AssgReadonly2,
ErrorCode.ERR_RefReturnReadonlyStatic2,
ErrorCode.ERR_RefReadonlyStatic2,
ErrorCode.ERR_AssgReadonlyStatic2
};
int index = (checkingReceiver ? 6 : 0) + (field.IsStatic ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2));
if (checkingReceiver)
{
Error(diagnostics, ReadOnlyErrors[index], node, field);
}
else
{
Error(diagnostics, ReadOnlyErrors[index], node);
}
}
private static void ReportReadOnlyError(Symbol symbol, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)symbol != null);
Debug.Assert(RequiresAssignableVariable(kind));
// It's clearer to say that the address can't be taken than to say that the parameter can't be modified
// (even though the latter message gives more explanation of why).
if (kind == BindValueKind.AddressOf)
{
Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node);
return;
}
var symbolKind = symbol.Kind.Localize();
ErrorCode[] ReadOnlyErrors =
{
ErrorCode.ERR_RefReturnReadonlyNotField,
ErrorCode.ERR_RefReadonlyNotField,
ErrorCode.ERR_AssignReadonlyNotField,
ErrorCode.ERR_RefReturnReadonlyNotField2,
ErrorCode.ERR_RefReadonlyNotField2,
ErrorCode.ERR_AssignReadonlyNotField2,
};
int index = (checkingReceiver ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2));
Error(diagnostics, ReadOnlyErrors[index], node, symbolKind, symbol);
}
/// <summary>
/// Checks whether given expression can escape from the current scope to the <paramref name="escapeTo"/>
/// In a case if it cannot a bad expression is returned and diagnostics is produced.
/// </summary>
internal BoundExpression ValidateEscape(BoundExpression expr, uint escapeTo, bool isByRef, BindingDiagnosticBag diagnostics)
{
if (isByRef)
{
if (CheckRefEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return expr;
}
}
else
{
if (CheckValEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return expr;
}
}
return ToBadExpression(expr);
}
/// <summary>
/// Computes the widest scope depth to which the given expression can escape by reference.
///
/// NOTE: in a case if expression cannot be passed by an alias (RValue and similar), the ref-escape is scopeOfTheContainingExpression
/// There are few cases where RValues are permitted to be passed by reference which implies that a temporary local proxy is passed instead.
/// We reflect such behavior by constraining the escape value to the narrowest scope possible.
/// </summary>
internal static uint GetRefEscape(BoundExpression expr, uint scopeOfTheContainingExpression)
{
// cannot infer anything from errors
if (expr.HasAnyErrors)
{
return Binder.ExternalScope;
}
// cannot infer anything from Void (broken code)
if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void)
{
return Binder.ExternalScope;
}
// constants/literals cannot ref-escape current scope
if (expr.ConstantValue != null)
{
return scopeOfTheContainingExpression;
}
// cover case that cannot refer to local state
// otherwise default to current scope (RValues, etc)
switch (expr.Kind)
{
case BoundKind.ArrayAccess:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
// array elements and pointer dereferencing are readwrite variables
return Binder.ExternalScope;
case BoundKind.RefValueOperator:
// The undocumented __refvalue(tr, T) expression results in an lvalue of type T.
// for compat reasons it is not ref-returnable (since TypedReference is not val-returnable)
// it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level)
return Binder.TopLevelScope;
case BoundKind.DiscardExpression:
// same as write-only byval local
break;
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
// dynamic expressions can be read and written to
// can even be passed by reference (which is implemented via a temp)
// it is not valid to escape them by reference though, so treat them as RValues here
break;
case BoundKind.Parameter:
var parameter = ((BoundParameter)expr).ParameterSymbol;
// byval parameters can escape to method's top level. Others can escape further.
// NOTE: "method" here means nearest containing method, lambda or local function.
return parameter.RefKind == RefKind.None ? Binder.TopLevelScope : Binder.ExternalScope;
case BoundKind.Local:
return ((BoundLocal)expr).LocalSymbol.RefEscapeScope;
case BoundKind.ThisReference:
var thisref = (BoundThisReference)expr;
// "this" is an RValue, unless in a struct.
if (!thisref.Type.IsValueType)
{
break;
}
//"this" is not returnable by reference in a struct.
// can ref escape to any other level
return Binder.TopLevelScope;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
if (conditional.IsRef)
{
// ref conditional defers to its operands
return Math.Max(GetRefEscape(conditional.Consequence, scopeOfTheContainingExpression),
GetRefEscape(conditional.Alternative, scopeOfTheContainingExpression));
}
// otherwise it is an RValue
break;
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
var fieldSymbol = fieldAccess.FieldSymbol;
// fields that are static or belong to reference types can ref escape anywhere
if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return Binder.ExternalScope;
}
// for other fields defer to the receiver.
return GetRefEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression);
case BoundKind.EventAccess:
var eventAccess = (BoundEventAccess)expr;
if (!eventAccess.IsUsableAsField)
{
// not field-like events are RValues
break;
}
var eventSymbol = eventAccess.EventSymbol;
// field-like events that are static or belong to reference types can ref escape anywhere
if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType)
{
return Binder.ExternalScope;
}
// for other events defer to the receiver.
return GetRefEscape(eventAccess.ReceiverOpt, scopeOfTheContainingExpression);
case BoundKind.Call:
var call = (BoundCall)expr;
var methodSymbol = call.Method;
if (methodSymbol.RefKind == RefKind.None)
{
break;
}
return GetInvocationEscapeScope(
call.Method,
call.ReceiverOpt,
methodSymbol.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.FunctionPointerInvocation:
var ptrInvocation = (BoundFunctionPointerInvocation)expr;
methodSymbol = ptrInvocation.FunctionPointer.Signature;
if (methodSymbol.RefKind == RefKind.None)
{
break;
}
return GetInvocationEscapeScope(
methodSymbol,
receiverOpt: null,
methodSymbol.Parameters,
ptrInvocation.Arguments,
ptrInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
return GetInvocationEscapeScope(
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
// not passing any arguments/parameters
return GetInvocationEscapeScope(
propertyAccess.PropertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
if (!assignment.IsRef)
{
// non-ref assignments are RValues
break;
}
return GetRefEscape(assignment.Left, scopeOfTheContainingExpression);
}
// At this point we should have covered all the possible cases for anything that is not a strict RValue.
return scopeOfTheContainingExpression;
}
/// <summary>
/// A counterpart to the GetRefEscape, which validates if given escape demand can be met by the expression.
/// The result indicates whether the escape is possible.
/// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure.
/// </summary>
internal static bool CheckRefEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter());
if (escapeTo >= escapeFrom)
{
// escaping to same or narrower scope is ok.
return true;
}
if (expr.HasAnyErrors)
{
// already an error
return true;
}
// void references cannot escape (error should be reported somewhere)
if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void)
{
return true;
}
// references to constants/literals cannot escape higher.
if (expr.ConstantValue != null)
{
Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node);
return false;
}
switch (expr.Kind)
{
case BoundKind.ArrayAccess:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
// array elements and pointer dereferencing are readwrite variables
return true;
case BoundKind.RefValueOperator:
// The undocumented __refvalue(tr, T) expression results in an lvalue of type T.
// for compat reasons it is not ref-returnable (since TypedReference is not val-returnable)
if (escapeTo == Binder.ExternalScope)
{
break;
}
// it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level)
return true;
case BoundKind.DiscardExpression:
// same as write-only byval local
break;
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
// dynamic expressions can be read and written to
// can even be passed by reference (which is implemented via a temp)
// it is not valid to escape them by reference though.
break;
case BoundKind.Parameter:
var parameter = (BoundParameter)expr;
return CheckParameterRefEscape(node, parameter, escapeTo, checkingReceiver, diagnostics);
case BoundKind.Local:
var local = (BoundLocal)expr;
return CheckLocalRefEscape(node, local, escapeTo, checkingReceiver, diagnostics);
case BoundKind.ThisReference:
var thisref = (BoundThisReference)expr;
// "this" is an RValue, unless in a struct.
if (!thisref.Type.IsValueType)
{
break;
}
//"this" is not returnable by reference in a struct.
if (escapeTo == Binder.ExternalScope)
{
Error(diagnostics, ErrorCode.ERR_RefReturnStructThis, node, ThisParameterSymbol.SymbolName);
return false;
}
// can ref escape to any other level
return true;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
if (conditional.IsRef)
{
return CheckRefEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckRefEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
}
// report standard lvalue error
break;
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
return CheckFieldRefEscape(node, fieldAccess, escapeFrom, escapeTo, diagnostics);
case BoundKind.EventAccess:
var eventAccess = (BoundEventAccess)expr;
if (!eventAccess.IsUsableAsField)
{
// not field-like events are RValues
break;
}
return CheckFieldLikeEventRefEscape(node, eventAccess, escapeFrom, escapeTo, diagnostics);
case BoundKind.Call:
var call = (BoundCall)expr;
var methodSymbol = call.Method;
if (methodSymbol.RefKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
call.Syntax,
methodSymbol,
call.ReceiverOpt,
methodSymbol.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
if (indexerSymbol.RefKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
indexerAccess.Syntax,
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
RefKind refKind;
ImmutableArray<ParameterSymbol> parameters;
switch (patternIndexer.PatternSymbol)
{
case PropertySymbol p:
refKind = p.RefKind;
parameters = p.Parameters;
break;
case MethodSymbol m:
refKind = m.RefKind;
parameters = m.Parameters;
break;
default:
throw ExceptionUtilities.Unreachable;
}
if (refKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
patternIndexer.Syntax,
patternIndexer.PatternSymbol,
patternIndexer.Receiver,
parameters,
ImmutableArray.Create<BoundExpression>(patternIndexer.Argument),
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.FunctionPointerInvocation:
var functionPointerInvocation = (BoundFunctionPointerInvocation)expr;
FunctionPointerMethodSymbol signature = functionPointerInvocation.FunctionPointer.Signature;
if (signature.RefKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
functionPointerInvocation.Syntax,
signature,
functionPointerInvocation.InvokedExpression,
signature.Parameters,
functionPointerInvocation.Arguments,
functionPointerInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
var propertySymbol = propertyAccess.PropertySymbol;
if (propertySymbol.RefKind == RefKind.None)
{
break;
}
// not passing any arguments/parameters
return CheckInvocationEscape(
propertyAccess.Syntax,
propertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
// Only ref-assignments can be LValues
if (!assignment.IsRef)
{
break;
}
return CheckRefEscape(
node,
assignment.Left,
escapeFrom,
escapeTo,
checkingReceiver: false,
diagnostics);
}
// At this point we should have covered all the possible cases for anything that is not a strict RValue.
Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node);
return false;
}
internal static uint GetBroadestValEscape(BoundTupleExpression expr, uint scopeOfTheContainingExpression)
{
uint broadest = scopeOfTheContainingExpression;
foreach (var element in expr.Arguments)
{
uint valEscape;
if (element is BoundTupleExpression te)
{
valEscape = GetBroadestValEscape(te, scopeOfTheContainingExpression);
}
else
{
valEscape = GetValEscape(element, scopeOfTheContainingExpression);
}
broadest = Math.Min(broadest, valEscape);
}
return broadest;
}
/// <summary>
/// Computes the widest scope depth to which the given expression can escape by value.
///
/// NOTE: unless the type of expression is ref-like, the result is Binder.ExternalScope since ordinary values can always be returned from methods.
/// </summary>
internal static uint GetValEscape(BoundExpression expr, uint scopeOfTheContainingExpression)
{
// cannot infer anything from errors
if (expr.HasAnyErrors)
{
return Binder.ExternalScope;
}
// constants/literals cannot refer to local state
if (expr.ConstantValue != null)
{
return Binder.ExternalScope;
}
// to have local-referring values an expression must have a ref-like type
if (expr.Type?.IsRefLikeType != true)
{
return Binder.ExternalScope;
}
// cover case that can refer to local state
// otherwise default to ExternalScope (ordinary values)
switch (expr.Kind)
{
case BoundKind.DefaultLiteral:
case BoundKind.DefaultExpression:
case BoundKind.Parameter:
case BoundKind.ThisReference:
// always returnable
return Binder.ExternalScope;
case BoundKind.TupleLiteral:
case BoundKind.ConvertedTupleLiteral:
var tupleLiteral = (BoundTupleExpression)expr;
return GetTupleValEscape(tupleLiteral.Arguments, scopeOfTheContainingExpression);
case BoundKind.MakeRefOperator:
case BoundKind.RefValueOperator:
// for compat reasons
// NB: it also means can`t assign stackalloc spans to a __refvalue
// we are ok with that.
return Binder.ExternalScope;
case BoundKind.DiscardExpression:
// same as uninitialized local
return Binder.ExternalScope;
case BoundKind.DeconstructValuePlaceholder:
return ((BoundDeconstructValuePlaceholder)expr).ValEscape;
case BoundKind.Local:
return ((BoundLocal)expr).LocalSymbol.ValEscapeScope;
case BoundKind.StackAllocArrayCreation:
case BoundKind.ConvertedStackAllocExpression:
return Binder.TopLevelScope;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
var consEscape = GetValEscape(conditional.Consequence, scopeOfTheContainingExpression);
if (conditional.IsRef)
{
// ref conditional defers to one operand.
// the other one is the same or we will be reporting errors anyways.
return consEscape;
}
// val conditional gets narrowest of its operands
return Math.Max(consEscape,
GetValEscape(conditional.Alternative, scopeOfTheContainingExpression));
case BoundKind.NullCoalescingOperator:
var coalescingOp = (BoundNullCoalescingOperator)expr;
return Math.Max(GetValEscape(coalescingOp.LeftOperand, scopeOfTheContainingExpression),
GetValEscape(coalescingOp.RightOperand, scopeOfTheContainingExpression));
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
var fieldSymbol = fieldAccess.FieldSymbol;
if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType)
{
// Already an error state.
return Binder.ExternalScope;
}
// for ref-like fields defer to the receiver.
return GetValEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression);
case BoundKind.Call:
var call = (BoundCall)expr;
return GetInvocationEscapeScope(
call.Method,
call.ReceiverOpt,
call.Method.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.FunctionPointerInvocation:
var ptrInvocation = (BoundFunctionPointerInvocation)expr;
var ptrSymbol = ptrInvocation.FunctionPointer.Signature;
return GetInvocationEscapeScope(
ptrSymbol,
receiverOpt: null,
ptrSymbol.Parameters,
ptrInvocation.Arguments,
ptrInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
return GetInvocationEscapeScope(
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
var parameters = patternIndexer.PatternSymbol switch
{
PropertySymbol p => p.Parameters,
MethodSymbol m => m.Parameters,
_ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol)
};
return GetInvocationEscapeScope(
patternIndexer.PatternSymbol,
patternIndexer.Receiver,
parameters,
default,
default,
default,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
// not passing any arguments/parameters
return GetInvocationEscapeScope(
propertyAccess.PropertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.ObjectCreationExpression:
var objectCreation = (BoundObjectCreationExpression)expr;
var constructorSymbol = objectCreation.Constructor;
var escape = GetInvocationEscapeScope(
constructorSymbol,
null,
constructorSymbol.Parameters,
objectCreation.Arguments,
objectCreation.ArgumentRefKindsOpt,
objectCreation.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: false);
var initializerOpt = objectCreation.InitializerExpressionOpt;
if (initializerOpt != null)
{
escape = Math.Max(escape, GetValEscape(initializerOpt, scopeOfTheContainingExpression));
}
return escape;
case BoundKind.WithExpression:
var withExpression = (BoundWithExpression)expr;
return Math.Max(GetValEscape(withExpression.Receiver, scopeOfTheContainingExpression),
GetValEscape(withExpression.InitializerExpression, scopeOfTheContainingExpression));
case BoundKind.UnaryOperator:
return GetValEscape(((BoundUnaryOperator)expr).Operand, scopeOfTheContainingExpression);
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected");
if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler)
{
return GetInterpolatedStringHandlerConversionEscapeScope((BoundInterpolatedString)conversion.Operand, scopeOfTheContainingExpression);
}
return GetValEscape(conversion.Operand, scopeOfTheContainingExpression);
case BoundKind.AssignmentOperator:
return GetValEscape(((BoundAssignmentOperator)expr).Right, scopeOfTheContainingExpression);
case BoundKind.IncrementOperator:
return GetValEscape(((BoundIncrementOperator)expr).Operand, scopeOfTheContainingExpression);
case BoundKind.CompoundAssignmentOperator:
var compound = (BoundCompoundAssignmentOperator)expr;
return Math.Max(GetValEscape(compound.Left, scopeOfTheContainingExpression),
GetValEscape(compound.Right, scopeOfTheContainingExpression));
case BoundKind.BinaryOperator:
var binary = (BoundBinaryOperator)expr;
return Math.Max(GetValEscape(binary.Left, scopeOfTheContainingExpression),
GetValEscape(binary.Right, scopeOfTheContainingExpression));
case BoundKind.UserDefinedConditionalLogicalOperator:
var uo = (BoundUserDefinedConditionalLogicalOperator)expr;
return Math.Max(GetValEscape(uo.Left, scopeOfTheContainingExpression),
GetValEscape(uo.Right, scopeOfTheContainingExpression));
case BoundKind.QueryClause:
return GetValEscape(((BoundQueryClause)expr).Value, scopeOfTheContainingExpression);
case BoundKind.RangeVariable:
return GetValEscape(((BoundRangeVariable)expr).Value, scopeOfTheContainingExpression);
case BoundKind.ObjectInitializerExpression:
var initExpr = (BoundObjectInitializerExpression)expr;
return GetValEscapeOfObjectInitializer(initExpr, scopeOfTheContainingExpression);
case BoundKind.CollectionInitializerExpression:
var colExpr = (BoundCollectionInitializerExpression)expr;
return GetValEscape(colExpr.Initializers, scopeOfTheContainingExpression);
case BoundKind.CollectionElementInitializer:
var colElement = (BoundCollectionElementInitializer)expr;
return GetValEscape(colElement.Arguments, scopeOfTheContainingExpression);
case BoundKind.ObjectInitializerMember:
// this node generally makes no sense outside of the context of containing initializer
// however binder uses it as a placeholder when binding assignments inside an object initializer
// just say it does not escape anywhere, so that we do not get false errors.
return scopeOfTheContainingExpression;
case BoundKind.ImplicitReceiver:
case BoundKind.ObjectOrCollectionValuePlaceholder:
// binder uses this as a placeholder when binding members inside an object initializer
// just say it does not escape anywhere, so that we do not get false errors.
return scopeOfTheContainingExpression;
case BoundKind.InterpolatedStringHandlerPlaceholder:
// The handler placeholder cannot escape out of the current expression, as it's a compiler-synthesized
// location.
return scopeOfTheContainingExpression;
case BoundKind.InterpolatedStringArgumentPlaceholder:
// We saved off the safe-to-escape of the argument when we did binding
return ((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape;
case BoundKind.DisposableValuePlaceholder:
// Disposable value placeholder is only ever used to lookup a pattern dispose method
// then immediately discarded. The actual expression will be generated during lowering
return scopeOfTheContainingExpression;
case BoundKind.AwaitableValuePlaceholder:
return ((BoundAwaitableValuePlaceholder)expr).ValEscape;
case BoundKind.PointerElementAccess:
case BoundKind.PointerIndirectionOperator:
// Unsafe code will always be allowed to escape.
return Binder.ExternalScope;
case BoundKind.AsOperator:
case BoundKind.AwaitExpression:
case BoundKind.ConditionalAccess:
case BoundKind.ArrayAccess:
// only possible in error cases (if possible at all)
return scopeOfTheContainingExpression;
case BoundKind.ConvertedSwitchExpression:
case BoundKind.UnconvertedSwitchExpression:
var switchExpr = (BoundSwitchExpression)expr;
return GetValEscape(switchExpr.SwitchArms.SelectAsArray(a => a.Value), scopeOfTheContainingExpression);
default:
// in error situations some unexpected nodes could make here
// returning "scopeOfTheContainingExpression" seems safer than throwing.
// we will still assert to make sure that all nodes are accounted for.
Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type");
return scopeOfTheContainingExpression;
}
}
private static uint GetTupleValEscape(ImmutableArray<BoundExpression> elements, uint scopeOfTheContainingExpression)
{
uint narrowestScope = scopeOfTheContainingExpression;
foreach (var element in elements)
{
narrowestScope = Math.Max(narrowestScope, GetValEscape(element, scopeOfTheContainingExpression));
}
return narrowestScope;
}
private static uint GetValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint scopeOfTheContainingExpression)
{
var result = Binder.ExternalScope;
foreach (var expression in initExpr.Initializers)
{
if (expression.Kind == BoundKind.AssignmentOperator)
{
var assignment = (BoundAssignmentOperator)expression;
result = Math.Max(result, GetValEscape(assignment.Right, scopeOfTheContainingExpression));
var left = (BoundObjectInitializerMember)assignment.Left;
result = Math.Max(result, GetValEscape(left.Arguments, scopeOfTheContainingExpression));
}
else
{
result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression));
}
}
return result;
}
private static uint GetValEscape(ImmutableArray<BoundExpression> expressions, uint scopeOfTheContainingExpression)
{
var result = Binder.ExternalScope;
foreach (var expression in expressions)
{
result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression));
}
return result;
}
/// <summary>
/// A counterpart to the GetValEscape, which validates if given escape demand can be met by the expression.
/// The result indicates whether the escape is possible.
/// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure.
/// </summary>
internal static bool CheckValEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter());
if (escapeTo >= escapeFrom)
{
// escaping to same or narrower scope is ok.
return true;
}
// cannot infer anything from errors
if (expr.HasAnyErrors)
{
return true;
}
// constants/literals cannot refer to local state
if (expr.ConstantValue != null)
{
return true;
}
// to have local-referring values an expression must have a ref-like type
if (expr.Type?.IsRefLikeType != true)
{
return true;
}
switch (expr.Kind)
{
case BoundKind.DefaultLiteral:
case BoundKind.DefaultExpression:
case BoundKind.Parameter:
case BoundKind.ThisReference:
// always returnable
return true;
case BoundKind.TupleLiteral:
case BoundKind.ConvertedTupleLiteral:
var tupleLiteral = (BoundTupleExpression)expr;
return CheckTupleValEscape(tupleLiteral.Arguments, escapeFrom, escapeTo, diagnostics);
case BoundKind.MakeRefOperator:
case BoundKind.RefValueOperator:
// for compat reasons
return true;
case BoundKind.DiscardExpression:
// same as uninitialized local
return true;
case BoundKind.DeconstructValuePlaceholder:
if (((BoundDeconstructValuePlaceholder)expr).ValEscape > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax);
return false;
}
return true;
case BoundKind.AwaitableValuePlaceholder:
if (((BoundAwaitableValuePlaceholder)expr).ValEscape > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax);
return false;
}
return true;
case BoundKind.InterpolatedStringArgumentPlaceholder:
if (((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax);
return false;
}
return true;
case BoundKind.Local:
var localSymbol = ((BoundLocal)expr).LocalSymbol;
if (localSymbol.ValEscapeScope > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol);
return false;
}
return true;
case BoundKind.StackAllocArrayCreation:
case BoundKind.ConvertedStackAllocExpression:
if (escapeTo < Binder.TopLevelScope)
{
Error(diagnostics, ErrorCode.ERR_EscapeStackAlloc, node, expr.Type);
return false;
}
return true;
case BoundKind.UnconvertedConditionalOperator:
{
var conditional = (BoundUnconvertedConditionalOperator)expr;
return
CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
}
case BoundKind.ConditionalOperator:
{
var conditional = (BoundConditionalOperator)expr;
var consValid = CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
if (!consValid || conditional.IsRef)
{
// ref conditional defers to one operand.
// the other one is the same or we will be reporting errors anyways.
return consValid;
}
return CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
}
case BoundKind.NullCoalescingOperator:
var coalescingOp = (BoundNullCoalescingOperator)expr;
return CheckValEscape(coalescingOp.LeftOperand.Syntax, coalescingOp.LeftOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics) &&
CheckValEscape(coalescingOp.RightOperand.Syntax, coalescingOp.RightOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics);
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
var fieldSymbol = fieldAccess.FieldSymbol;
if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType)
{
// Already an error state.
return true;
}
// for ref-like fields defer to the receiver.
return CheckValEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, true, diagnostics);
case BoundKind.Call:
var call = (BoundCall)expr;
var methodSymbol = call.Method;
return CheckInvocationEscape(
call.Syntax,
methodSymbol,
call.ReceiverOpt,
methodSymbol.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.FunctionPointerInvocation:
var ptrInvocation = (BoundFunctionPointerInvocation)expr;
var ptrSymbol = ptrInvocation.FunctionPointer.Signature;
return CheckInvocationEscape(
ptrInvocation.Syntax,
ptrSymbol,
receiverOpt: null,
ptrSymbol.Parameters,
ptrInvocation.Arguments,
ptrInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
return CheckInvocationEscape(
indexerAccess.Syntax,
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
var patternSymbol = patternIndexer.PatternSymbol;
var parameters = patternSymbol switch
{
PropertySymbol p => p.Parameters,
MethodSymbol m => m.Parameters,
_ => throw ExceptionUtilities.Unreachable,
};
return CheckInvocationEscape(
patternIndexer.Syntax,
patternSymbol,
patternIndexer.Receiver,
parameters,
ImmutableArray.Create(patternIndexer.Argument),
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
// not passing any arguments/parameters
return CheckInvocationEscape(
propertyAccess.Syntax,
propertyAccess.PropertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.ObjectCreationExpression:
{
var objectCreation = (BoundObjectCreationExpression)expr;
var constructorSymbol = objectCreation.Constructor;
var escape = CheckInvocationEscape(
objectCreation.Syntax,
constructorSymbol,
null,
constructorSymbol.Parameters,
objectCreation.Arguments,
objectCreation.ArgumentRefKindsOpt,
objectCreation.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
var initializerExpr = objectCreation.InitializerExpressionOpt;
if (initializerExpr != null)
{
escape = escape &&
CheckValEscape(
initializerExpr.Syntax,
initializerExpr,
escapeFrom,
escapeTo,
checkingReceiver: false,
diagnostics: diagnostics);
}
return escape;
}
case BoundKind.WithExpression:
{
var withExpr = (BoundWithExpression)expr;
var escape = CheckValEscape(node, withExpr.Receiver, escapeFrom, escapeTo, checkingReceiver: false, diagnostics);
var initializerExpr = withExpr.InitializerExpression;
escape = escape && CheckValEscape(initializerExpr.Syntax, initializerExpr, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
return escape;
}
case BoundKind.UnaryOperator:
var unary = (BoundUnaryOperator)expr;
return CheckValEscape(node, unary.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected");
if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler)
{
return CheckInterpolatedStringHandlerConversionEscape((BoundInterpolatedString)conversion.Operand, escapeFrom, escapeTo, diagnostics);
}
return CheckValEscape(node, conversion.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
return CheckValEscape(node, assignment.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.IncrementOperator:
var increment = (BoundIncrementOperator)expr;
return CheckValEscape(node, increment.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.CompoundAssignmentOperator:
var compound = (BoundCompoundAssignmentOperator)expr;
return CheckValEscape(compound.Left.Syntax, compound.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(compound.Right.Syntax, compound.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.BinaryOperator:
var binary = (BoundBinaryOperator)expr;
return CheckValEscape(binary.Left.Syntax, binary.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(binary.Right.Syntax, binary.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.UserDefinedConditionalLogicalOperator:
var uo = (BoundUserDefinedConditionalLogicalOperator)expr;
return CheckValEscape(uo.Left.Syntax, uo.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(uo.Right.Syntax, uo.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.QueryClause:
var clauseValue = ((BoundQueryClause)expr).Value;
return CheckValEscape(clauseValue.Syntax, clauseValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.RangeVariable:
var variableValue = ((BoundRangeVariable)expr).Value;
return CheckValEscape(variableValue.Syntax, variableValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.ObjectInitializerExpression:
var initExpr = (BoundObjectInitializerExpression)expr;
return CheckValEscapeOfObjectInitializer(initExpr, escapeFrom, escapeTo, diagnostics);
// this would be correct implementation for CollectionInitializerExpression
// however it is unclear if it is reachable since the initialized type must implement IEnumerable
case BoundKind.CollectionInitializerExpression:
var colExpr = (BoundCollectionInitializerExpression)expr;
return CheckValEscape(colExpr.Initializers, escapeFrom, escapeTo, diagnostics);
// this would be correct implementation for CollectionElementInitializer
// however it is unclear if it is reachable since the initialized type must implement IEnumerable
case BoundKind.CollectionElementInitializer:
var colElement = (BoundCollectionElementInitializer)expr;
return CheckValEscape(colElement.Arguments, escapeFrom, escapeTo, diagnostics);
case BoundKind.PointerElementAccess:
var accessedExpression = ((BoundPointerElementAccess)expr).Expression;
return CheckValEscape(accessedExpression.Syntax, accessedExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics);
case BoundKind.PointerIndirectionOperator:
var operandExpression = ((BoundPointerIndirectionOperator)expr).Operand;
return CheckValEscape(operandExpression.Syntax, operandExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics);
case BoundKind.AsOperator:
case BoundKind.AwaitExpression:
case BoundKind.ConditionalAccess:
case BoundKind.ArrayAccess:
// only possible in error cases (if possible at all)
return false;
case BoundKind.UnconvertedSwitchExpression:
case BoundKind.ConvertedSwitchExpression:
foreach (var arm in ((BoundSwitchExpression)expr).SwitchArms)
{
var result = arm.Value;
if (!CheckValEscape(result.Syntax, result, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
return false;
}
return true;
default:
// in error situations some unexpected nodes could make here
// returning "false" seems safer than throwing.
// we will still assert to make sure that all nodes are accounted for.
Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type");
diagnostics.Add(ErrorCode.ERR_InternalError, node.Location);
return false;
#region "cannot produce ref-like values"
// case BoundKind.ThrowExpression:
// case BoundKind.ArgListOperator:
// case BoundKind.ArgList:
// case BoundKind.RefTypeOperator:
// case BoundKind.AddressOfOperator:
// case BoundKind.TypeOfOperator:
// case BoundKind.IsOperator:
// case BoundKind.SizeOfOperator:
// case BoundKind.DynamicMemberAccess:
// case BoundKind.DynamicInvocation:
// case BoundKind.NewT:
// case BoundKind.DelegateCreationExpression:
// case BoundKind.ArrayCreation:
// case BoundKind.AnonymousObjectCreationExpression:
// case BoundKind.NameOfOperator:
// case BoundKind.InterpolatedString:
// case BoundKind.StringInsert:
// case BoundKind.DynamicIndexerAccess:
// case BoundKind.Lambda:
// case BoundKind.DynamicObjectCreationExpression:
// case BoundKind.NoPiaObjectCreationExpression:
// case BoundKind.BaseReference:
// case BoundKind.Literal:
// case BoundKind.IsPatternExpression:
// case BoundKind.DeconstructionAssignmentOperator:
// case BoundKind.EventAccess:
#endregion
#region "not expression that can produce a value"
// case BoundKind.FieldEqualsValue:
// case BoundKind.PropertyEqualsValue:
// case BoundKind.ParameterEqualsValue:
// case BoundKind.NamespaceExpression:
// case BoundKind.TypeExpression:
// case BoundKind.BadStatement:
// case BoundKind.MethodDefIndex:
// case BoundKind.SourceDocumentIndex:
// case BoundKind.ArgList:
// case BoundKind.ArgListOperator:
// case BoundKind.Block:
// case BoundKind.Scope:
// case BoundKind.NoOpStatement:
// case BoundKind.ReturnStatement:
// case BoundKind.YieldReturnStatement:
// case BoundKind.YieldBreakStatement:
// case BoundKind.ThrowStatement:
// case BoundKind.ExpressionStatement:
// case BoundKind.SwitchStatement:
// case BoundKind.SwitchSection:
// case BoundKind.SwitchLabel:
// case BoundKind.BreakStatement:
// case BoundKind.LocalFunctionStatement:
// case BoundKind.ContinueStatement:
// case BoundKind.PatternSwitchStatement:
// case BoundKind.PatternSwitchSection:
// case BoundKind.PatternSwitchLabel:
// case BoundKind.IfStatement:
// case BoundKind.DoStatement:
// case BoundKind.WhileStatement:
// case BoundKind.ForStatement:
// case BoundKind.ForEachStatement:
// case BoundKind.ForEachDeconstructStep:
// case BoundKind.UsingStatement:
// case BoundKind.FixedStatement:
// case BoundKind.LockStatement:
// case BoundKind.TryStatement:
// case BoundKind.CatchBlock:
// case BoundKind.LabelStatement:
// case BoundKind.GotoStatement:
// case BoundKind.LabeledStatement:
// case BoundKind.Label:
// case BoundKind.StatementList:
// case BoundKind.ConditionalGoto:
// case BoundKind.LocalDeclaration:
// case BoundKind.MultipleLocalDeclarations:
// case BoundKind.ArrayInitialization:
// case BoundKind.AnonymousPropertyDeclaration:
// case BoundKind.MethodGroup:
// case BoundKind.PropertyGroup:
// case BoundKind.EventAssignmentOperator:
// case BoundKind.Attribute:
// case BoundKind.FixedLocalCollectionInitializer:
// case BoundKind.DynamicObjectInitializerMember:
// case BoundKind.DynamicCollectionElementInitializer:
// case BoundKind.ImplicitReceiver:
// case BoundKind.FieldInitializer:
// case BoundKind.GlobalStatementInitializer:
// case BoundKind.TypeOrInstanceInitializers:
// case BoundKind.DeclarationPattern:
// case BoundKind.ConstantPattern:
// case BoundKind.WildcardPattern:
#endregion
#region "not found as an operand in no-error unlowered bound tree"
// case BoundKind.MaximumMethodDefIndex:
// case BoundKind.InstrumentationPayloadRoot:
// case BoundKind.ModuleVersionId:
// case BoundKind.ModuleVersionIdString:
// case BoundKind.Dup:
// case BoundKind.TypeOrValueExpression:
// case BoundKind.BadExpression:
// case BoundKind.ArrayLength:
// case BoundKind.MethodInfo:
// case BoundKind.FieldInfo:
// case BoundKind.SequencePoint:
// case BoundKind.SequencePointExpression:
// case BoundKind.SequencePointWithSpan:
// case BoundKind.StateMachineScope:
// case BoundKind.ConditionalReceiver:
// case BoundKind.ComplexConditionalReceiver:
// case BoundKind.PreviousSubmissionReference:
// case BoundKind.HostObjectMemberReference:
// case BoundKind.UnboundLambda:
// case BoundKind.LoweredConditionalAccess:
// case BoundKind.Sequence:
// case BoundKind.HoistedFieldAccess:
// case BoundKind.OutVariablePendingInference:
// case BoundKind.DeconstructionVariablePendingInference:
// case BoundKind.OutDeconstructVarPendingInference:
// case BoundKind.PseudoVariable:
#endregion
}
}
private static bool CheckTupleValEscape(ImmutableArray<BoundExpression> elements, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
foreach (var element in elements)
{
if (!CheckValEscape(element.Syntax, element, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
}
return true;
}
private static bool CheckValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
foreach (var expression in initExpr.Initializers)
{
if (expression.Kind == BoundKind.AssignmentOperator)
{
var assignment = (BoundAssignmentOperator)expression;
if (!CheckValEscape(expression.Syntax, assignment.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
var left = (BoundObjectInitializerMember)assignment.Left;
if (!CheckValEscape(left.Arguments, escapeFrom, escapeTo, diagnostics: diagnostics))
{
return false;
}
}
else
{
if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
}
}
return true;
}
private static bool CheckValEscape(ImmutableArray<BoundExpression> expressions, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
foreach (var expression in expressions)
{
if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
}
return true;
}
private static bool CheckInterpolatedStringHandlerConversionEscape(BoundInterpolatedString interpolatedString, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
Debug.Assert(interpolatedString.InterpolationData is not null);
// We need to check to see if any values could potentially escape outside the max depth via the handler type.
// Consider the case where a ref-struct handler saves off the result of one call to AppendFormatted,
// and then on a subsequent call it either assigns that saved value to another ref struct with a larger
// escape, or does the opposite. In either case, we need to check.
CheckValEscape(interpolatedString.Syntax, interpolatedString.InterpolationData.GetValueOrDefault().Construction, escapeFrom, escapeTo, checkingReceiver: false, diagnostics);
foreach (var part in interpolatedString.Parts)
{
if (part is not BoundCall { Method: { Name: "AppendFormatted" } } call)
{
// Dynamic calls cannot have ref struct parameters, and AppendLiteral calls will always have literal
// string arguments and do not require us to be concerned with escape
continue;
}
// The interpolation component is always the first argument to the method, and it was not passed by name
// so there can be no reordering.
var argument = call.Arguments[0];
var success = CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, checkingReceiver: false, diagnostics);
if (!success)
{
return false;
}
}
return true;
}
internal enum AddressKind
{
// reference may be written to
Writeable,
// reference itself will not be written to, but may be used for call, callvirt.
// for all purposes it is the same as Writeable, except when fetching an address of an array element
// where it results in a ".readonly" prefix to deal with array covariance.
Constrained,
// reference itself will not be written to, nor it will be used to modify fields.
ReadOnly,
// same as ReadOnly, but we are not supposed to get a reference to a clone
// regardless of compat settings.
ReadOnlyStrict,
}
internal static bool IsAnyReadOnly(AddressKind addressKind) => addressKind >= AddressKind.ReadOnly;
/// <summary>
/// Checks if expression directly or indirectly represents a value with its own home. In
/// such cases it is possible to get a reference without loading into a temporary.
/// </summary>
internal static bool HasHome(
BoundExpression expression,
AddressKind addressKind,
MethodSymbol method,
bool peVerifyCompatEnabled,
HashSet<LocalSymbol> stackLocalsOpt)
{
Debug.Assert(method is object);
switch (expression.Kind)
{
case BoundKind.ArrayAccess:
if (addressKind == AddressKind.ReadOnly && !expression.Type.IsValueType && peVerifyCompatEnabled)
{
// due to array covariance getting a reference may throw ArrayTypeMismatch when element is not a struct,
// passing "readonly." prefix would prevent that, but it is unverifiable, so will make a copy in compat case
return false;
}
return true;
case BoundKind.PointerIndirectionOperator:
case BoundKind.RefValueOperator:
return true;
case BoundKind.ThisReference:
var type = expression.Type;
if (type.IsReferenceType)
{
Debug.Assert(IsAnyReadOnly(addressKind), "`this` is readonly in classes");
return true;
}
if (!IsAnyReadOnly(addressKind) && method.IsEffectivelyReadOnly)
{
return false;
}
return true;
case BoundKind.ThrowExpression:
// vacuously this is true, we can take address of throw without temps
return true;
case BoundKind.Parameter:
return IsAnyReadOnly(addressKind) ||
((BoundParameter)expression).ParameterSymbol.RefKind != RefKind.In;
case BoundKind.Local:
// locals have home unless they are byval stack locals or ref-readonly
// locals in a mutating call
var local = ((BoundLocal)expression).LocalSymbol;
return !((CodeGenerator.IsStackLocal(local, stackLocalsOpt) && local.RefKind == RefKind.None) ||
(!IsAnyReadOnly(addressKind) && local.RefKind == RefKind.RefReadOnly));
case BoundKind.Call:
var methodRefKind = ((BoundCall)expression).Method.RefKind;
return methodRefKind == RefKind.Ref ||
(IsAnyReadOnly(addressKind) && methodRefKind == RefKind.RefReadOnly);
case BoundKind.Dup:
//NB: Dup represents locals that do not need IL slot
var dupRefKind = ((BoundDup)expression).RefKind;
return dupRefKind == RefKind.Ref ||
(IsAnyReadOnly(addressKind) && dupRefKind == RefKind.RefReadOnly);
case BoundKind.FieldAccess:
return HasHome((BoundFieldAccess)expression, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt);
case BoundKind.Sequence:
return HasHome(((BoundSequence)expression).Value, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expression;
if (!assignment.IsRef)
{
return false;
}
var lhsRefKind = assignment.Left.GetRefKind();
return lhsRefKind == RefKind.Ref ||
(IsAnyReadOnly(addressKind) && lhsRefKind == RefKind.RefReadOnly);
case BoundKind.ComplexConditionalReceiver:
Debug.Assert(HasHome(
((BoundComplexConditionalReceiver)expression).ValueTypeReceiver,
addressKind,
method,
peVerifyCompatEnabled,
stackLocalsOpt));
Debug.Assert(HasHome(
((BoundComplexConditionalReceiver)expression).ReferenceTypeReceiver,
addressKind,
method,
peVerifyCompatEnabled,
stackLocalsOpt));
goto case BoundKind.ConditionalReceiver;
case BoundKind.ConditionalReceiver:
//ConditionalReceiver is a noop from Emit point of view. - it represents something that has already been pushed.
//We should never need a temp for it.
return true;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expression;
// only ref conditional may be referenced as a variable
if (!conditional.IsRef)
{
return false;
}
// branch that has no home will need a temporary
// if both have no home, just say whole expression has no home
// so we could just use one temp for the whole thing
return HasHome(conditional.Consequence, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)
&& HasHome(conditional.Alternative, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt);
default:
return false;
}
}
/// <summary>
/// Special HasHome for fields.
/// Fields have readable homes when they are not constants.
/// Fields have writeable homes unless they are readonly and used outside of the constructor.
/// </summary>
private static bool HasHome(
BoundFieldAccess fieldAccess,
AddressKind addressKind,
MethodSymbol method,
bool peVerifyCompatEnabled,
HashSet<LocalSymbol> stackLocalsOpt)
{
Debug.Assert(method is object);
FieldSymbol field = fieldAccess.FieldSymbol;
// const fields are literal values with no homes. (ex: decimal.Zero)
if (field.IsConst)
{
return false;
}
// in readonly situations where ref to a copy is not allowed, consider fields as addressable
if (addressKind == AddressKind.ReadOnlyStrict)
{
return true;
}
// ReadOnly references can always be taken unless we are in peverify compat mode
if (addressKind == AddressKind.ReadOnly && !peVerifyCompatEnabled)
{
return true;
}
// Some field accesses must be values; values do not have homes.
if (fieldAccess.IsByValue)
{
return false;
}
if (!field.IsReadOnly)
{
// in a case if we have a writeable struct field with a receiver that only has a readable home we would need to pass it via a temp.
// it would be advantageous to make a temp for the field, not for the outer struct, since the field is smaller and we can get to is by fetching references.
// NOTE: this would not be profitable if we have to satisfy verifier, since for verifiability
// we would not be able to dig for the inner field using references and the outer struct will have to be copied to a temp anyways.
if (!peVerifyCompatEnabled)
{
Debug.Assert(!IsAnyReadOnly(addressKind));
var receiver = fieldAccess.ReceiverOpt;
if (receiver?.Type.IsValueType == true)
{
// Check receiver:
// has writeable home -> return true - the whole chain has writeable home (also a more common case)
// has readable home -> return false - we need to copy the field
// otherwise -> return true - the copy will be made at higher level so the leaf field can have writeable home
return HasHome(receiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)
|| !HasHome(receiver, AddressKind.ReadOnly, method, peVerifyCompatEnabled, stackLocalsOpt);
}
}
return true;
}
// while readonly fields have home it is not valid to refer to it when not constructing.
if (!TypeSymbol.Equals(field.ContainingType, method.ContainingType, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
if (field.IsStatic)
{
return method.MethodKind == MethodKind.StaticConstructor;
}
else
{
return (method.MethodKind == MethodKind.Constructor || method.IsInitOnly) &&
fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class Binder
{
/// <summary>
/// For the purpose of escape verification we operate with the depth of local scopes.
/// The depth is a uint, with smaller number representing shallower/wider scopes.
/// The 0 and 1 are special scopes -
/// 0 is the "external" or "return" scope that is outside of the containing method/lambda.
/// If something can escape to scope 0, it can escape to any scope in a given method or can be returned.
/// 1 is the "parameter" or "top" scope that is just inside the containing method/lambda.
/// If something can escape to scope 1, it can escape to any scope in a given method, but cannot be returned.
/// n + 1 corresponds to scopes immediately inside a scope of depth n.
/// Since sibling scopes do not intersect and a value cannot escape from one to another without
/// escaping to a wider scope, we can use simple depth numbering without ambiguity.
/// </summary>
internal const uint ExternalScope = 0;
internal const uint TopLevelScope = 1;
// Some value kinds are semantically the same and the only distinction is how errors are reported
// for those purposes we reserve lowest 2 bits
private const int ValueKindInsignificantBits = 2;
private const BindValueKind ValueKindSignificantBitsMask = unchecked((BindValueKind)~((1 << ValueKindInsignificantBits) - 1));
/// <summary>
/// Expression capabilities and requirements.
/// </summary>
[Flags]
internal enum BindValueKind : ushort
{
///////////////////
// All expressions can be classified according to the following 4 capabilities:
//
/// <summary>
/// Expression can be an RHS of an assignment operation.
/// </summary>
/// <remarks>
/// The following are rvalues: values, variables, null literals, properties
/// and indexers with getters, events.
///
/// The following are not rvalues:
/// namespaces, types, method groups, anonymous functions.
/// </remarks>
RValue = 1 << ValueKindInsignificantBits,
/// <summary>
/// Expression can be the LHS of a simple assignment operation.
/// Example:
/// property with a setter
/// </summary>
Assignable = 2 << ValueKindInsignificantBits,
/// <summary>
/// Expression represents a location. Often referred as a "variable"
/// Examples:
/// local variable, parameter, field
/// </summary>
RefersToLocation = 4 << ValueKindInsignificantBits,
/// <summary>
/// Expression can be the LHS of a ref-assign operation.
/// Example:
/// ref local, ref parameter, out parameter
/// </summary>
RefAssignable = 8 << ValueKindInsignificantBits,
///////////////////
// The rest are just combinations of the above.
//
/// <summary>
/// Expression is the RHS of an assignment operation
/// and may be a method group.
/// Basically an RValue, but could be treated differently for the purpose of error reporting
/// </summary>
RValueOrMethodGroup = RValue + 1,
/// <summary>
/// Expression can be an LHS of a compound assignment
/// operation (such as +=).
/// </summary>
CompoundAssignment = RValue | Assignable,
/// <summary>
/// Expression can be the operand of an increment or decrement operation.
/// Same as CompoundAssignment, the distinction is really just for error reporting.
/// </summary>
IncrementDecrement = CompoundAssignment + 1,
/// <summary>
/// Expression is a r/o reference.
/// </summary>
ReadonlyRef = RefersToLocation | RValue,
/// <summary>
/// Expression can be the operand of an address-of operation (&).
/// Same as ReadonlyRef. The difference is just for error reporting.
/// </summary>
AddressOf = ReadonlyRef + 1,
/// <summary>
/// Expression is the receiver of a fixed buffer field access
/// Same as ReadonlyRef. The difference is just for error reporting.
/// </summary>
FixedReceiver = ReadonlyRef + 2,
/// <summary>
/// Expression is passed as a ref or out parameter or assigned to a byref variable.
/// </summary>
RefOrOut = RefersToLocation | RValue | Assignable,
/// <summary>
/// Expression is returned by an ordinary r/w reference.
/// Same as RefOrOut. The difference is just for error reporting.
/// </summary>
RefReturn = RefOrOut + 1,
}
private static bool RequiresRValueOnly(BindValueKind kind)
{
return (kind & ValueKindSignificantBitsMask) == BindValueKind.RValue;
}
private static bool RequiresAssignmentOnly(BindValueKind kind)
{
return (kind & ValueKindSignificantBitsMask) == BindValueKind.Assignable;
}
private static bool RequiresVariable(BindValueKind kind)
{
return !RequiresRValueOnly(kind);
}
private static bool RequiresReferenceToLocation(BindValueKind kind)
{
return (kind & BindValueKind.RefersToLocation) != 0;
}
private static bool RequiresAssignableVariable(BindValueKind kind)
{
return (kind & BindValueKind.Assignable) != 0;
}
private static bool RequiresRefAssignableVariable(BindValueKind kind)
{
return (kind & BindValueKind.RefAssignable) != 0;
}
private static bool RequiresRefOrOut(BindValueKind kind)
{
return (kind & BindValueKind.RefOrOut) == BindValueKind.RefOrOut;
}
#nullable enable
private BoundIndexerAccess BindIndexerDefaultArguments(BoundIndexerAccess indexerAccess, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
var useSetAccessor = valueKind == BindValueKind.Assignable && !indexerAccess.Indexer.ReturnsByRef;
var accessorForDefaultArguments = useSetAccessor
? indexerAccess.Indexer.GetOwnOrInheritedSetMethod()
: indexerAccess.Indexer.GetOwnOrInheritedGetMethod();
if (accessorForDefaultArguments is not null)
{
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(accessorForDefaultArguments.ParameterCount);
argumentsBuilder.AddRange(indexerAccess.Arguments);
ArrayBuilder<RefKind>? refKindsBuilderOpt;
if (!indexerAccess.ArgumentRefKindsOpt.IsDefaultOrEmpty)
{
refKindsBuilderOpt = ArrayBuilder<RefKind>.GetInstance(accessorForDefaultArguments.ParameterCount);
refKindsBuilderOpt.AddRange(indexerAccess.ArgumentRefKindsOpt);
}
else
{
refKindsBuilderOpt = null;
}
var argsToParams = indexerAccess.ArgsToParamsOpt;
// It is possible for the indexer 'value' parameter from metadata to have a default value, but the compiler will not use it.
// However, we may still use any default values from the preceding parameters.
var parameters = accessorForDefaultArguments.Parameters;
if (useSetAccessor)
{
parameters = parameters.RemoveAt(parameters.Length - 1);
}
BitVector defaultArguments = default;
Debug.Assert(parameters.Length == indexerAccess.Indexer.Parameters.Length);
// If OriginalIndexersOpt is set, there was an overload resolution failure, and we don't want to make guesses about the default
// arguments that will end up being reflected in the SemanticModel/IOperation
if (indexerAccess.OriginalIndexersOpt.IsDefault)
{
BindDefaultArguments(indexerAccess.Syntax, parameters, argumentsBuilder, refKindsBuilderOpt, ref argsToParams, out defaultArguments, indexerAccess.Expanded, enableCallerInfo: true, diagnostics);
}
indexerAccess = indexerAccess.Update(
indexerAccess.ReceiverOpt,
indexerAccess.Indexer,
argumentsBuilder.ToImmutableAndFree(),
indexerAccess.ArgumentNamesOpt,
refKindsBuilderOpt?.ToImmutableOrNull() ?? default,
indexerAccess.Expanded,
argsToParams,
defaultArguments,
indexerAccess.Type);
refKindsBuilderOpt?.Free();
}
return indexerAccess;
}
#nullable disable
/// <summary>
/// Check the expression is of the required lvalue and rvalue specified by valueKind.
/// The method returns the original expression if the expression is of the required
/// type. Otherwise, an appropriate error is added to the diagnostics bag and the
/// method returns a BoundBadExpression node. The method returns the original
/// expression without generating any error if the expression has errors.
/// </summary>
private BoundExpression CheckValue(BoundExpression expr, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
switch (expr.Kind)
{
case BoundKind.PropertyGroup:
expr = BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics);
if (expr is BoundIndexerAccess indexerAccess)
{
expr = BindIndexerDefaultArguments(indexerAccess, valueKind, diagnostics);
}
break;
case BoundKind.Local:
Debug.Assert(expr.Syntax.Kind() != SyntaxKind.Argument || valueKind == BindValueKind.RefOrOut);
break;
case BoundKind.OutVariablePendingInference:
case BoundKind.OutDeconstructVarPendingInference:
Debug.Assert(valueKind == BindValueKind.RefOrOut);
return expr;
case BoundKind.DiscardExpression:
Debug.Assert(valueKind == BindValueKind.Assignable || valueKind == BindValueKind.RefOrOut || diagnostics.DiagnosticBag is null || diagnostics.HasAnyResolvedErrors());
return expr;
case BoundKind.IndexerAccess:
expr = BindIndexerDefaultArguments((BoundIndexerAccess)expr, valueKind, diagnostics);
break;
case BoundKind.UnconvertedObjectCreationExpression:
if (valueKind == BindValueKind.RValue)
{
return expr;
}
break;
}
bool hasResolutionErrors = false;
// If this a MethodGroup where an rvalue is not expected or where the caller will not explicitly handle
// (and resolve) MethodGroups (in short, cases where valueKind != BindValueKind.RValueOrMethodGroup),
// resolve the MethodGroup here to generate the appropriate errors, otherwise resolution errors (such as
// "member is inaccessible") will be dropped.
if (expr.Kind == BoundKind.MethodGroup && valueKind != BindValueKind.RValueOrMethodGroup)
{
var methodGroup = (BoundMethodGroup)expr;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo);
diagnostics.Add(expr.Syntax, useSiteInfo);
Symbol otherSymbol = null;
bool resolvedToMethodGroup = resolution.MethodGroup != null;
if (!expr.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading.
hasResolutionErrors = resolution.HasAnyErrors;
if (hasResolutionErrors)
{
otherSymbol = resolution.OtherSymbol;
}
resolution.Free();
// It's possible the method group is not a method group at all, but simply a
// delayed lookup that resolved to a non-method member (perhaps an inaccessible
// field or property), or nothing at all. In those cases, the member should not be exposed as a
// method group, not even within a BoundBadExpression. Instead, the
// BoundBadExpression simply refers to the receiver and the resolved symbol (if any).
if (!resolvedToMethodGroup)
{
Debug.Assert(methodGroup.ResultKind != LookupResultKind.Viable);
var receiver = methodGroup.ReceiverOpt;
if ((object)otherSymbol != null && receiver?.Kind == BoundKind.TypeOrValueExpression)
{
// Since we're not accessing a method, this can't be a Color Color case, so TypeOrValueExpression should not have been used.
// CAVEAT: otherSymbol could be invalid in some way (e.g. inaccessible), in which case we would have fallen back on a
// method group lookup (to allow for extension methods), which would have required a TypeOrValueExpression.
Debug.Assert(methodGroup.LookupError != null);
// Since we have a concrete member in hand, we can resolve the receiver.
var typeOrValue = (BoundTypeOrValueExpression)receiver;
receiver = otherSymbol.RequiresInstanceReceiver()
? typeOrValue.Data.ValueExpression
: null; // no receiver required
}
return new BoundBadExpression(
expr.Syntax,
methodGroup.ResultKind,
(object)otherSymbol == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(otherSymbol),
receiver == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(receiver),
GetNonMethodMemberType(otherSymbol));
}
}
if (!hasResolutionErrors && CheckValueKind(expr.Syntax, expr, valueKind, checkingReceiver: false, diagnostics: diagnostics) ||
expr.HasAnyErrors && valueKind == BindValueKind.RValueOrMethodGroup)
{
return expr;
}
var resultKind = (valueKind == BindValueKind.RValue || valueKind == BindValueKind.RValueOrMethodGroup) ?
LookupResultKind.NotAValue :
LookupResultKind.NotAVariable;
return ToBadExpression(expr, resultKind);
}
internal static bool IsTypeOrValueExpression(BoundExpression expression)
{
switch (expression?.Kind)
{
case BoundKind.TypeOrValueExpression:
case BoundKind.QueryClause when ((BoundQueryClause)expression).Value.Kind == BoundKind.TypeOrValueExpression:
return true;
default:
return false;
}
}
/// <summary>
/// The purpose of this method is to determine if the expression satisfies desired capabilities.
/// If it is not then this code gives an appropriate error message.
///
/// To determine the appropriate error message we need to know two things:
///
/// (1) What capabilities we need - increment it, assign, return as a readonly reference, . . . ?
///
/// (2) Are we trying to determine if the left hand side of a dot is a variable in order
/// to determine if the field or property on the right hand side of a dot is assignable?
///
/// (3) The syntax of the expression that started the analysis. (for error reporting purposes).
/// </summary>
internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter());
if (expr.HasAnyErrors)
{
return false;
}
switch (expr.Kind)
{
// we need to handle properties and event in a special way even in an RValue case because of getters
case BoundKind.PropertyAccess:
case BoundKind.IndexerAccess:
return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = ((BoundIndexOrRangePatternIndexerAccess)expr);
if (patternIndexer.PatternSymbol.Kind == SymbolKind.Property)
{
// If this is an Index indexer, PatternSymbol should be a property, pointing to the
// pattern indexer. If it's a Range access, it will be a method, pointing to a Slice method
// and it's handled below as part of invocations.
return CheckPropertyValueKind(node, expr, valueKind, checkingReceiver, diagnostics);
}
Debug.Assert(patternIndexer.PatternSymbol.Kind == SymbolKind.Method);
break;
case BoundKind.EventAccess:
return CheckEventValueKind((BoundEventAccess)expr, valueKind, diagnostics);
}
// easy out for a very common RValue case.
if (RequiresRValueOnly(valueKind))
{
return CheckNotNamespaceOrType(expr, diagnostics);
}
// constants/literals are strictly RValues
// void is not even an RValue
if ((expr.ConstantValue != null) || (expr.Type.GetSpecialTypeSafe() == SpecialType.System_Void))
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
switch (expr.Kind)
{
case BoundKind.NamespaceExpression:
var ns = (BoundNamespaceExpression)expr;
Error(diagnostics, ErrorCode.ERR_BadSKknown, node, ns.NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.TypeExpression:
var type = (BoundTypeExpression)expr;
Error(diagnostics, ErrorCode.ERR_BadSKknown, node, type.Type, MessageID.IDS_SK_TYPE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.Lambda:
case BoundKind.UnboundLambda:
// lambdas can only be used as RValues
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
case BoundKind.UnconvertedAddressOfOperator:
var unconvertedAddressOf = (BoundUnconvertedAddressOfOperator)expr;
Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, unconvertedAddressOf.Operand.Name, MessageID.IDS_AddressOfMethodGroup.Localize());
return false;
case BoundKind.MethodGroup when valueKind == BindValueKind.AddressOf:
// If the addressof operator is used not as an rvalue, that will get flagged when CheckValue
// is called on the parent BoundUnconvertedAddressOf node.
return true;
case BoundKind.MethodGroup:
// method groups can only be used as RValues except when taking the address of one
var methodGroup = (BoundMethodGroup)expr;
Error(diagnostics, GetMethodGroupOrFunctionPointerLvalueError(valueKind), node, methodGroup.Name, MessageID.IDS_MethodGroup.Localize());
return false;
case BoundKind.RangeVariable:
// range variables can only be used as RValues
var queryref = (BoundRangeVariable)expr;
Error(diagnostics, GetRangeLvalueError(valueKind), node, queryref.RangeVariableSymbol.Name);
return false;
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
// conversions are strict RValues, but unboxing has a specific error
if (conversion.ConversionKind == ConversionKind.Unboxing)
{
Error(diagnostics, ErrorCode.ERR_UnboxNotLValue, node);
return false;
}
break;
// array access is readwrite variable if the indexing expression is not System.Range
case BoundKind.ArrayAccess:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
var boundAccess = (BoundArrayAccess)expr;
if (boundAccess.Indices.Length == 1 &&
TypeSymbol.Equals(
boundAccess.Indices[0].Type,
Compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything))
{
// Range indexer is an rvalue
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
return true;
}
// pointer dereferencing is a readwrite variable
case BoundKind.PointerIndirectionOperator:
// The undocumented __refvalue(tr, T) expression results in a variable of type T.
case BoundKind.RefValueOperator:
// dynamic expressions are readwrite, and can even be passed by ref (which is implemented via a temp)
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// These are readwrite variables
return true;
}
case BoundKind.PointerElementAccess:
{
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
var receiver = ((BoundPointerElementAccess)expr).Expression;
if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer)
{
return CheckValueKind(node, fieldAccess.ReceiverOpt, valueKind, checkingReceiver: true, diagnostics);
}
return true;
}
case BoundKind.Parameter:
var parameter = (BoundParameter)expr;
return CheckParameterValueKind(node, parameter, valueKind, checkingReceiver, diagnostics);
case BoundKind.Local:
var local = (BoundLocal)expr;
return CheckLocalValueKind(node, local, valueKind, checkingReceiver, diagnostics);
case BoundKind.ThisReference:
// `this` is never ref assignable
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// We will already have given an error for "this" used outside of a constructor,
// instance method, or instance accessor. Assume that "this" is a variable if it is in a struct.
// SPEC: when this is used in a primary-expression within an instance constructor of a struct,
// SPEC: it is classified as a variable.
// SPEC: When this is used in a primary-expression within an instance method or instance accessor
// SPEC: of a struct, it is classified as a variable.
// Note: RValueOnly is checked at the beginning of this method. Since we are here we need more than readable.
// "this" is readonly in members marked "readonly" and in members of readonly structs, unless we are in a constructor.
var isValueType = ((BoundThisReference)expr).Type.IsValueType;
if (!isValueType || (RequiresAssignableVariable(valueKind) && (this.ContainingMemberOrLambda as MethodSymbol)?.IsEffectivelyReadOnly == true))
{
Error(diagnostics, GetThisLvalueError(valueKind, isValueType), node, node);
return false;
}
return true;
case BoundKind.ImplicitReceiver:
case BoundKind.ObjectOrCollectionValuePlaceholder:
Debug.Assert(!RequiresRefAssignableVariable(valueKind));
return true;
case BoundKind.Call:
var call = (BoundCall)expr;
return CheckCallValueKind(call, node, valueKind, checkingReceiver, diagnostics);
case BoundKind.FunctionPointerInvocation:
return CheckMethodReturnValueKind(((BoundFunctionPointerInvocation)expr).FunctionPointer.Signature,
expr.Syntax,
node,
valueKind,
checkingReceiver,
diagnostics);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
// If we got here this should be a pattern indexer taking a Range,
// meaning that the pattern symbol must be a method (either Slice or Substring)
return CheckMethodReturnValueKind(
(MethodSymbol)patternIndexer.PatternSymbol,
patternIndexer.Syntax,
node,
valueKind,
checkingReceiver,
diagnostics);
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
// byref conditional defers to its operands
if (conditional.IsRef &&
(CheckValueKind(conditional.Consequence.Syntax, conditional.Consequence, valueKind, checkingReceiver: false, diagnostics: diagnostics) &
CheckValueKind(conditional.Alternative.Syntax, conditional.Alternative, valueKind, checkingReceiver: false, diagnostics: diagnostics)))
{
return true;
}
// report standard lvalue error
break;
case BoundKind.FieldAccess:
{
var fieldAccess = (BoundFieldAccess)expr;
return CheckFieldValueKind(node, fieldAccess, valueKind, checkingReceiver, diagnostics);
}
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
return CheckSimpleAssignmentValueKind(node, assignment, valueKind, diagnostics);
}
// At this point we should have covered all the possible cases for anything that is not a strict RValue.
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
private static bool CheckNotNamespaceOrType(BoundExpression expr, BindingDiagnosticBag diagnostics)
{
switch (expr.Kind)
{
case BoundKind.NamespaceExpression:
Error(diagnostics, ErrorCode.ERR_BadSKknown, expr.Syntax, ((BoundNamespaceExpression)expr).NamespaceSymbol, MessageID.IDS_SK_NAMESPACE.Localize(), MessageID.IDS_SK_VARIABLE.Localize());
return false;
case BoundKind.TypeExpression:
Error(diagnostics, ErrorCode.ERR_BadSKunknown, expr.Syntax, expr.Type, MessageID.IDS_SK_TYPE.Localize());
return false;
default:
return true;
}
}
private bool CheckLocalValueKind(SyntaxNode node, BoundLocal local, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
// Local constants are never variables. Local variables are sometimes
// not to be treated as variables, if they are fixed, declared in a using,
// or declared in a foreach.
LocalSymbol localSymbol = local.LocalSymbol;
if (RequiresAssignableVariable(valueKind))
{
if (this.LockedOrDisposedVariables.Contains(localSymbol))
{
diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, local.Syntax.Location, localSymbol);
}
// IsWritable means the variable is writable. If this is a ref variable, IsWritable
// does not imply anything about the storage location
if (localSymbol.RefKind == RefKind.RefReadOnly ||
(localSymbol.RefKind == RefKind.None && !localSymbol.IsWritableVariable))
{
ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics);
return false;
}
}
else if (RequiresRefAssignableVariable(valueKind))
{
if (localSymbol.RefKind == RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_RefLocalOrParamExpected, node.Location, localSymbol);
return false;
}
else if (!localSymbol.IsWritableVariable)
{
ReportReadonlyLocalError(node, localSymbol, valueKind, checkingReceiver, diagnostics);
return false;
}
}
return true;
}
private static bool CheckLocalRefEscape(SyntaxNode node, BoundLocal local, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
LocalSymbol localSymbol = local.LocalSymbol;
// if local symbol can escape to the same or wider/shallower scope then escapeTo
// then it is all ok, otherwise it is an error.
if (localSymbol.RefEscapeScope <= escapeTo)
{
return true;
}
if (escapeTo == Binder.ExternalScope)
{
if (localSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnLocal, node, localSymbol);
}
return false;
}
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal2, local.Syntax, localSymbol);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnNonreturnableLocal, node, localSymbol);
}
return false;
}
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol);
return false;
}
private bool CheckParameterValueKind(SyntaxNode node, BoundParameter parameter, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
ParameterSymbol parameterSymbol = parameter.ParameterSymbol;
// all parameters can be passed by ref/out or assigned to
// except "in" parameters, which are readonly
if (parameterSymbol.RefKind == RefKind.In && RequiresAssignableVariable(valueKind))
{
ReportReadOnlyError(parameterSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
else if (parameterSymbol.RefKind == RefKind.None && RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
if (this.LockedOrDisposedVariables.Contains(parameterSymbol))
{
// Consider: It would be more conventional to pass "symbol" rather than "symbol.Name".
// The issue is that the error SymbolDisplayFormat doesn't display parameter
// names - only their types - which works great in signatures, but not at all
// at the top level.
diagnostics.Add(ErrorCode.WRN_AssignmentToLockOrDispose, parameter.Syntax.Location, parameterSymbol.Name);
}
return true;
}
private static bool CheckParameterRefEscape(SyntaxNode node, BoundParameter parameter, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
ParameterSymbol parameterSymbol = parameter.ParameterSymbol;
// byval parameters can escape to method's top level. Others can escape further.
// NOTE: "method" here means nearest containing method, lambda or local function.
if (escapeTo == Binder.ExternalScope && parameterSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
Error(diagnostics, ErrorCode.ERR_RefReturnParameter2, parameter.Syntax, parameterSymbol.Name);
}
else
{
Error(diagnostics, ErrorCode.ERR_RefReturnParameter, node, parameterSymbol.Name);
}
return false;
}
// can ref-escape to any scope otherwise
return true;
}
private bool CheckFieldValueKind(SyntaxNode node, BoundFieldAccess fieldAccess, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
var fieldSymbol = fieldAccess.FieldSymbol;
var fieldIsStatic = fieldSymbol.IsStatic;
if (RequiresAssignableVariable(valueKind))
{
// A field is writeable unless
// (1) it is readonly and we are not in a constructor or field initializer
// (2) the receiver of the field is of value type and is not a variable or object creation expression.
// For example, if you have a class C with readonly field f of type S, and
// S has a mutable field x, then c.f.x is not a variable because c.f is not
// writable.
if (fieldSymbol.IsReadOnly)
{
var canModifyReadonly = false;
Symbol containing = this.ContainingMemberOrLambda;
if ((object)containing != null &&
fieldIsStatic == containing.IsStatic &&
(fieldIsStatic || fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference) &&
(Compilation.FeatureStrictEnabled
? TypeSymbol.Equals(fieldSymbol.ContainingType, containing.ContainingType, TypeCompareKind.ConsiderEverything2)
// We duplicate a bug in the native compiler for compatibility in non-strict mode
: TypeSymbol.Equals(fieldSymbol.ContainingType.OriginalDefinition, containing.ContainingType.OriginalDefinition, TypeCompareKind.ConsiderEverything2)))
{
if (containing.Kind == SymbolKind.Method)
{
MethodSymbol containingMethod = (MethodSymbol)containing;
MethodKind desiredMethodKind = fieldIsStatic ? MethodKind.StaticConstructor : MethodKind.Constructor;
canModifyReadonly = (containingMethod.MethodKind == desiredMethodKind) ||
isAssignedFromInitOnlySetterOnThis(fieldAccess.ReceiverOpt);
}
else if (containing.Kind == SymbolKind.Field)
{
canModifyReadonly = true;
}
}
if (!canModifyReadonly)
{
ReportReadOnlyFieldError(fieldSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
}
if (fieldSymbol.IsFixedSizeBuffer)
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
}
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
// r/w fields that are static or belong to reference types are writeable and returnable
if (fieldIsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other fields defer to the receiver.
return CheckIsValidReceiverForVariable(node, fieldAccess.ReceiverOpt, valueKind, diagnostics);
bool isAssignedFromInitOnlySetterOnThis(BoundExpression receiver)
{
// bad: other.readonlyField = ...
// bad: base.readonlyField = ...
if (!(receiver is BoundThisReference))
{
return false;
}
if (!(ContainingMemberOrLambda is MethodSymbol method))
{
return false;
}
return method.IsInitOnly;
}
}
private bool CheckSimpleAssignmentValueKind(SyntaxNode node, BoundAssignmentOperator assignment, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
// Only ref-assigns produce LValues
if (assignment.IsRef)
{
return CheckValueKind(node, assignment.Left, valueKind, checkingReceiver: false, diagnostics);
}
Error(diagnostics, GetStandardLvalueError(valueKind), node);
return false;
}
private static bool CheckFieldRefEscape(SyntaxNode node, BoundFieldAccess fieldAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
var fieldSymbol = fieldAccess.FieldSymbol;
// fields that are static or belong to reference types can ref escape anywhere
if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other fields defer to the receiver.
return CheckRefEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics);
}
private static bool CheckFieldLikeEventRefEscape(SyntaxNode node, BoundEventAccess eventAccess, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
var eventSymbol = eventAccess.EventSymbol;
// field-like events that are static or belong to reference types can ref escape anywhere
if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType)
{
return true;
}
// for other events defer to the receiver.
return CheckRefEscape(node, eventAccess.ReceiverOpt, escapeFrom, escapeTo, checkingReceiver: true, diagnostics: diagnostics);
}
private bool CheckEventValueKind(BoundEventAccess boundEvent, BindValueKind valueKind, BindingDiagnosticBag diagnostics)
{
// Compound assignment (actually "event assignment") is allowed "everywhere", subject to the restrictions of
// accessibility, use site errors, and receiver variable-ness (for structs).
// Other operations are allowed only for field-like events and only where the backing field is accessible
// (i.e. in the declaring type) - subject to use site errors and receiver variable-ness.
BoundExpression receiver = boundEvent.ReceiverOpt;
SyntaxNode eventSyntax = GetEventName(boundEvent); //does not include receiver
EventSymbol eventSymbol = boundEvent.EventSymbol;
if (valueKind == BindValueKind.CompoundAssignment)
{
// NOTE: accessibility has already been checked by lookup.
// NOTE: availability of well-known members is checked in BindEventAssignment because
// we don't have the context to determine whether addition or subtraction is being performed.
if (ReportUseSite(eventSymbol, diagnostics, eventSyntax))
{
// NOTE: BindEventAssignment checks use site errors on the specific accessor
// (since we don't know which is being used).
return false;
}
Debug.Assert(!RequiresVariableReceiver(receiver, eventSymbol));
return true;
}
else
{
if (!boundEvent.IsUsableAsField)
{
// Dev10 reports this in addition to ERR_BadAccess, but we won't even reach this point if the event isn't accessible (caught by lookup).
Error(diagnostics, GetBadEventUsageDiagnosticInfo(eventSymbol), eventSyntax);
return false;
}
else if (ReportUseSite(eventSymbol, diagnostics, eventSyntax))
{
if (!CheckIsValidReceiverForVariable(eventSyntax, receiver, BindValueKind.Assignable, diagnostics))
{
return false;
}
}
else if (RequiresVariable(valueKind))
{
if (eventSymbol.IsWindowsRuntimeEvent && valueKind != BindValueKind.Assignable)
{
// NOTE: Dev11 reports ERR_RefProperty, as if this were a property access (since that's how it will be lowered).
// Roslyn reports a new, more specific, error code.
ErrorCode errorCode = valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_WinRtEventPassedByRef : GetStandardLvalueError(valueKind);
Error(diagnostics, errorCode, eventSyntax, eventSymbol);
return false;
}
else if (RequiresVariableReceiver(receiver, eventSymbol.AssociatedField) && // NOTE: using field, not event
!CheckIsValidReceiverForVariable(eventSyntax, receiver, valueKind, diagnostics))
{
return false;
}
}
return true;
}
}
private bool CheckIsValidReceiverForVariable(SyntaxNode node, BoundExpression receiver, BindValueKind kind, BindingDiagnosticBag diagnostics)
{
Debug.Assert(receiver != null);
return Flags.Includes(BinderFlags.ObjectInitializerMember) && receiver.Kind == BoundKind.ObjectOrCollectionValuePlaceholder ||
CheckValueKind(node, receiver, kind, true, diagnostics);
}
/// <summary>
/// SPEC: When a property or indexer declared in a struct-type is the target of an
/// SPEC: assignment, the instance expression associated with the property or indexer
/// SPEC: access must be classified as a variable. If the instance expression is
/// SPEC: classified as a value, a compile-time error occurs. Because of 7.6.4,
/// SPEC: the same rule also applies to fields.
/// </summary>
/// <remarks>
/// NOTE: The spec fails to impose the restriction that the event receiver must be classified
/// as a variable (unlike for properties - 7.17.1). This seems like a bug, but we have
/// production code that won't build with the restriction in place (see DevDiv #15674).
/// </remarks>
private static bool RequiresVariableReceiver(BoundExpression receiver, Symbol symbol)
{
return symbol.RequiresInstanceReceiver()
&& symbol.Kind != SymbolKind.Event
&& receiver?.Type?.IsValueType == true;
}
private bool CheckCallValueKind(BoundCall call, SyntaxNode node, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
=> CheckMethodReturnValueKind(call.Method, call.Syntax, node, valueKind, checkingReceiver, diagnostics);
protected bool CheckMethodReturnValueKind(
MethodSymbol methodSymbol,
SyntaxNode callSyntaxOpt,
SyntaxNode node,
BindValueKind valueKind,
bool checkingReceiver,
BindingDiagnosticBag diagnostics)
{
// A call can only be a variable if it returns by reference. If this is the case,
// whether or not it is a valid variable depends on whether or not the call is the
// RHS of a return or an assign by reference:
// - If call is used in a context demanding ref-returnable reference all of its ref
// inputs must be ref-returnable
if (RequiresVariable(valueKind) && methodSymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
// Error is associated with expression, not node which may be distinct.
Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, callSyntaxOpt, methodSymbol);
}
else
{
Error(diagnostics, GetStandardLvalueError(valueKind), node);
}
return false;
}
if (RequiresAssignableVariable(valueKind) && methodSymbol.RefKind == RefKind.RefReadOnly)
{
ReportReadOnlyError(methodSymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
return true;
}
private bool CheckPropertyValueKind(SyntaxNode node, BoundExpression expr, BindValueKind valueKind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
// SPEC: If the left operand is a property or indexer access, the property or indexer must
// SPEC: have a set accessor. If this is not the case, a compile-time error occurs.
// Addendum: Assignment is also allowed for get-only autoprops in their constructor
BoundExpression receiver;
SyntaxNode propertySyntax;
var propertySymbol = GetPropertySymbol(expr, out receiver, out propertySyntax);
Debug.Assert((object)propertySymbol != null);
Debug.Assert(propertySyntax != null);
if ((RequiresReferenceToLocation(valueKind) || checkingReceiver) &&
propertySymbol.RefKind == RefKind.None)
{
if (checkingReceiver)
{
// Error is associated with expression, not node which may be distinct.
// This error is reported for all values types. That is a breaking
// change from Dev10 which reports this error for struct types only,
// not for type parameters constrained to "struct".
Debug.Assert(propertySymbol.TypeWithAnnotations.HasType);
Error(diagnostics, ErrorCode.ERR_ReturnNotLValue, expr.Syntax, propertySymbol);
}
else
{
Error(diagnostics, valueKind == BindValueKind.RefOrOut ? ErrorCode.ERR_RefProperty : GetStandardLvalueError(valueKind), node, propertySymbol);
}
return false;
}
if (RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.RefReadOnly)
{
ReportReadOnlyError(propertySymbol, node, valueKind, checkingReceiver, diagnostics);
return false;
}
var requiresSet = RequiresAssignableVariable(valueKind) && propertySymbol.RefKind == RefKind.None;
if (requiresSet)
{
var setMethod = propertySymbol.GetOwnOrInheritedSetMethod();
if (setMethod is null)
{
var containing = this.ContainingMemberOrLambda;
if (!AccessingAutoPropertyFromConstructor(receiver, propertySymbol, containing)
&& !isAllowedDespiteReadonly(receiver))
{
Error(diagnostics, ErrorCode.ERR_AssgReadonlyProp, node, propertySymbol);
return false;
}
}
else
{
if (setMethod.IsInitOnly)
{
if (!isAllowedInitOnlySet(receiver))
{
Error(diagnostics, ErrorCode.ERR_AssignmentInitOnly, node, propertySymbol);
return false;
}
if (setMethod.DeclaringCompilation != this.Compilation)
{
// an error would have already been reported on declaring an init-only setter
CheckFeatureAvailability(node, MessageID.IDS_FeatureInitOnlySetters, diagnostics);
}
}
var accessThroughType = this.GetAccessThroughType(receiver);
bool failedThroughTypeCheck;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
bool isAccessible = this.IsAccessible(setMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!isAccessible)
{
if (failedThroughTypeCheck)
{
Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType);
}
else
{
Error(diagnostics, ErrorCode.ERR_InaccessibleSetter, node, propertySymbol);
}
return false;
}
ReportDiagnosticsIfObsolete(diagnostics, setMethod, node, receiver?.Kind == BoundKind.BaseReference);
var setValueKind = setMethod.IsEffectivelyReadOnly ? BindValueKind.RValue : BindValueKind.Assignable;
if (RequiresVariableReceiver(receiver, setMethod) && !CheckIsValidReceiverForVariable(node, receiver, setValueKind, diagnostics))
{
return false;
}
if (IsBadBaseAccess(node, receiver, setMethod, diagnostics, propertySymbol) ||
reportUseSite(setMethod))
{
return false;
}
CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, setMethod, diagnostics);
}
}
var requiresGet = !RequiresAssignmentOnly(valueKind) || propertySymbol.RefKind != RefKind.None;
if (requiresGet)
{
var getMethod = propertySymbol.GetOwnOrInheritedGetMethod();
if ((object)getMethod == null)
{
Error(diagnostics, ErrorCode.ERR_PropertyLacksGet, node, propertySymbol);
return false;
}
else
{
var accessThroughType = this.GetAccessThroughType(receiver);
bool failedThroughTypeCheck;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
bool isAccessible = this.IsAccessible(getMethod, accessThroughType, out failedThroughTypeCheck, ref useSiteInfo);
diagnostics.Add(node, useSiteInfo);
if (!isAccessible)
{
if (failedThroughTypeCheck)
{
Error(diagnostics, ErrorCode.ERR_BadProtectedAccess, node, propertySymbol, accessThroughType, this.ContainingType);
}
else
{
Error(diagnostics, ErrorCode.ERR_InaccessibleGetter, node, propertySymbol);
}
return false;
}
CheckImplicitThisCopyInReadOnlyMember(receiver, getMethod, diagnostics);
ReportDiagnosticsIfObsolete(diagnostics, getMethod, node, receiver?.Kind == BoundKind.BaseReference);
if (IsBadBaseAccess(node, receiver, getMethod, diagnostics, propertySymbol) ||
reportUseSite(getMethod))
{
return false;
}
CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, getMethod, diagnostics);
}
}
if (RequiresRefAssignableVariable(valueKind))
{
Error(diagnostics, ErrorCode.ERR_RefLocalOrParamExpected, node);
return false;
}
return true;
bool reportUseSite(MethodSymbol accessor)
{
UseSiteInfo<AssemblySymbol> useSiteInfo = accessor.GetUseSiteInfo();
if (!object.Equals(useSiteInfo.DiagnosticInfo, propertySymbol.GetUseSiteInfo().DiagnosticInfo))
{
return diagnostics.Add(useSiteInfo, propertySyntax);
}
else
{
diagnostics.AddDependencies(useSiteInfo);
}
return false;
}
static bool isAllowedDespiteReadonly(BoundExpression receiver)
{
// ok: anonymousType with { Property = ... }
if (receiver is BoundObjectOrCollectionValuePlaceholder && receiver.Type.IsAnonymousType)
{
return true;
}
return false;
}
bool isAllowedInitOnlySet(BoundExpression receiver)
{
// ok: new C() { InitOnlyProperty = ... }
// bad: { ... = { InitOnlyProperty = ... } }
if (receiver is BoundObjectOrCollectionValuePlaceholder placeholder)
{
return placeholder.IsNewInstance;
}
// bad: other.InitOnlyProperty = ...
if (!(receiver is BoundThisReference || receiver is BoundBaseReference))
{
return false;
}
var containingMember = ContainingMemberOrLambda;
if (!(containingMember is MethodSymbol method))
{
return false;
}
if (method.MethodKind == MethodKind.Constructor || method.IsInitOnly)
{
// ok: setting on `this` or `base` from an instance constructor or init-only setter
return true;
}
return false;
}
}
private bool IsBadBaseAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol member, BindingDiagnosticBag diagnostics,
Symbol propertyOrEventSymbolOpt = null)
{
Debug.Assert(member.Kind != SymbolKind.Property);
Debug.Assert(member.Kind != SymbolKind.Event);
if (receiverOpt?.Kind == BoundKind.BaseReference && member.IsAbstract)
{
Error(diagnostics, ErrorCode.ERR_AbstractBaseCall, node, propertyOrEventSymbolOpt ?? member);
return true;
}
return false;
}
internal static uint GetInterpolatedStringHandlerConversionEscapeScope(
BoundInterpolatedString interpolatedString,
uint scopeOfTheContainingExpression)
{
Debug.Assert(interpolatedString.InterpolationData != null);
var data = interpolatedString.InterpolationData.GetValueOrDefault();
return GetValEscape(data.Construction, scopeOfTheContainingExpression);
}
/// <summary>
/// Computes the scope to which the given invocation can escape
/// NOTE: the escape scope for ref and val escapes is the same for invocations except for trivial cases (ordinary type returned by val)
/// where escape is known otherwise. Therefore we do not vave two ref/val variants of this.
///
/// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as
/// local variables declared at the scope of the invocation.
/// </summary>
internal static uint GetInvocationEscapeScope(
Symbol symbol,
BoundExpression receiverOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<BoundExpression> argsOpt,
ImmutableArray<RefKind> argRefKindsOpt,
ImmutableArray<int> argsToParamsOpt,
uint scopeOfTheContainingExpression,
bool isRefEscape
)
{
// SPEC: (also applies to the CheckInvocationEscape counterpart)
//
// An lvalue resulting from a ref-returning method invocation e1.M(e2, ...) is ref-safe - to - escape the smallest of the following scopes:
//• The entire enclosing method
//• the ref-safe-to-escape of all ref/out/in argument expressions(excluding the receiver)
//• the safe-to - escape of all argument expressions(including the receiver)
//
// An rvalue resulting from a method invocation e1.M(e2, ...) is safe - to - escape from the smallest of the following scopes:
//• The entire enclosing method
//• the safe-to-escape of all argument expressions(including the receiver)
//
if (!symbol.RequiresInstanceReceiver())
{
// ignore receiver when symbol is static
receiverOpt = null;
}
//by default it is safe to escape
uint escapeScope = Binder.ExternalScope;
ArrayBuilder<bool> inParametersMatchedWithArgs = null;
if (!argsOpt.IsDefault)
{
moreArguments:
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
var argList = (BoundArgListOperator)argument;
// unwrap varargs and process as more arguments
argsOpt = argList.Arguments;
// ref kinds of varargs are not interesting here.
// __refvalue is not ref-returnable, so ref varargs can't come back from a call
argRefKindsOpt = default;
parameters = ImmutableArray<ParameterSymbol>.Empty;
argsToParamsOpt = default;
goto moreArguments;
}
RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs);
// ref escape scope is the narrowest of
// - ref escape of all byref arguments
// - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result)
//
// val escape scope is the narrowest of
// - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes)
var argEscape = effectiveRefKind != RefKind.None && isRefEscape ?
GetRefEscape(argument, scopeOfTheContainingExpression) :
GetValEscape(argument, scopeOfTheContainingExpression);
escapeScope = Math.Max(escapeScope, argEscape);
if (escapeScope >= scopeOfTheContainingExpression)
{
// no longer needed
inParametersMatchedWithArgs?.Free();
// can't get any worse
return escapeScope;
}
}
}
// handle omitted optional "in" parameters if there are any
ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs);
// unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse)
// its val escape is ExternalScope (does not affect overall result)
if (unmatchedInParameter != null && isRefEscape)
{
return scopeOfTheContainingExpression;
}
// check receiver if ref-like
if (receiverOpt?.Type?.IsRefLikeType == true)
{
escapeScope = Math.Max(escapeScope, GetValEscape(receiverOpt, scopeOfTheContainingExpression));
}
return escapeScope;
}
/// <summary>
/// Validates whether given invocation can allow its results to escape from <paramref name="escapeFrom"/> level to <paramref name="escapeTo"/> level.
/// The result indicates whether the escape is possible.
/// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure.
///
/// NOTE: we need scopeOfTheContainingExpression as some expressions such as optional <c>in</c> parameters or <c>ref dynamic</c> behave as
/// local variables declared at the scope of the invocation.
/// </summary>
private static bool CheckInvocationEscape(
SyntaxNode syntax,
Symbol symbol,
BoundExpression receiverOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<BoundExpression> argsOpt,
ImmutableArray<RefKind> argRefKindsOpt,
ImmutableArray<int> argsToParamsOpt,
bool checkingReceiver,
uint escapeFrom,
uint escapeTo,
BindingDiagnosticBag diagnostics,
bool isRefEscape
)
{
// SPEC:
// In a method invocation, the following constraints apply:
//• If there is a ref or out argument to a ref struct type (including the receiver), with safe-to-escape E1, then
// o no ref or out argument(excluding the receiver and arguments of ref-like types) may have a narrower ref-safe-to-escape than E1; and
// o no argument(including the receiver) may have a narrower safe-to-escape than E1.
if (!symbol.RequiresInstanceReceiver())
{
// ignore receiver when symbol is static
receiverOpt = null;
}
ArrayBuilder<bool> inParametersMatchedWithArgs = null;
if (!argsOpt.IsDefault)
{
moreArguments:
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
var argList = (BoundArgListOperator)argument;
// unwrap varargs and process as more arguments
argsOpt = argList.Arguments;
// ref kinds of varargs are not interesting here.
// __refvalue is not ref-returnable, so ref varargs can't come back from a call
argRefKindsOpt = default;
parameters = ImmutableArray<ParameterSymbol>.Empty;
argsToParamsOpt = default;
goto moreArguments;
}
RefKind effectiveRefKind = GetEffectiveRefKindAndMarkMatchedInParameter(argIndex, argRefKindsOpt, parameters, argsToParamsOpt, ref inParametersMatchedWithArgs);
// ref escape scope is the narrowest of
// - ref escape of all byref arguments
// - val escape of all byval arguments (ref-like values can be unwrapped into refs, so treat val escape of values as possible ref escape of the result)
//
// val escape scope is the narrowest of
// - val escape of all byval arguments (refs cannot be wrapped into values, so their ref escape is irrelevant, only use val escapes)
var valid = effectiveRefKind != RefKind.None && isRefEscape ?
CheckRefEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics) :
CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, false, diagnostics);
if (!valid)
{
// no longer needed
inParametersMatchedWithArgs?.Free();
ErrorCode errorCode = GetStandardCallEscapeError(checkingReceiver);
string parameterName;
if (parameters.Length > 0)
{
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
parameterName = parameters[paramIndex].Name;
if (string.IsNullOrEmpty(parameterName))
{
parameterName = paramIndex.ToString();
}
}
else
{
parameterName = "__arglist";
}
Error(diagnostics, errorCode, syntax, symbol, parameterName);
return false;
}
}
}
// handle omitted optional "in" parameters if there are any
ParameterSymbol unmatchedInParameter = TryGetunmatchedInParameterAndFreeMatchedArgs(parameters, ref inParametersMatchedWithArgs);
// unmatched "in" parameter is the same as a literal, its ref escape is scopeOfTheContainingExpression (can't get any worse)
// its val escape is ExternalScope (does not affect overall result)
if (unmatchedInParameter != null && isRefEscape)
{
var parameterName = unmatchedInParameter.Name;
if (string.IsNullOrEmpty(parameterName))
{
parameterName = unmatchedInParameter.Ordinal.ToString();
}
Error(diagnostics, GetStandardCallEscapeError(checkingReceiver), syntax, symbol, parameterName);
return false;
}
// check receiver if ref-like
if (receiverOpt?.Type?.IsRefLikeType == true)
{
return CheckValEscape(receiverOpt.Syntax, receiverOpt, escapeFrom, escapeTo, false, diagnostics);
}
return true;
}
/// <summary>
/// Validates whether the invocation is valid per no-mixing rules.
/// Returns <see langword="false"/> when it is not valid and produces diagnostics (possibly more than one recursively) that helps to figure the reason.
/// </summary>
private static bool CheckInvocationArgMixing(
SyntaxNode syntax,
Symbol symbol,
BoundExpression receiverOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<BoundExpression> argsOpt,
ImmutableArray<int> argsToParamsOpt,
uint scopeOfTheContainingExpression,
BindingDiagnosticBag diagnostics)
{
// SPEC:
// In a method invocation, the following constraints apply:
// - If there is a ref or out argument of a ref struct type (including the receiver), with safe-to-escape E1, then
// - no argument (including the receiver) may have a narrower safe-to-escape than E1.
if (!symbol.RequiresInstanceReceiver())
{
// ignore receiver when symbol is static
receiverOpt = null;
}
// widest possible escape via writeable ref-like receiver or ref/out argument.
uint escapeTo = scopeOfTheContainingExpression;
// collect all writeable ref-like arguments, including receiver
var receiverType = receiverOpt?.Type;
if (receiverType?.IsRefLikeType == true && !isReceiverRefReadOnly(symbol))
{
escapeTo = GetValEscape(receiverOpt, scopeOfTheContainingExpression);
}
if (!argsOpt.IsDefault)
{
BoundArgListOperator argList = null;
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
argList = (BoundArgListOperator)argument;
break;
}
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
if (parameters[paramIndex].RefKind.IsWritableReference() && argument.Type?.IsRefLikeType == true)
{
escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression));
}
}
if (argList != null)
{
var argListArgs = argList.Arguments;
var argListRefKindsOpt = argList.ArgumentRefKindsOpt;
for (var argIndex = 0; argIndex < argListArgs.Length; argIndex++)
{
var argument = argListArgs[argIndex];
var refKind = argListRefKindsOpt.IsDefault ? RefKind.None : argListRefKindsOpt[argIndex];
if (refKind.IsWritableReference() && argument.Type?.IsRefLikeType == true)
{
escapeTo = Math.Min(escapeTo, GetValEscape(argument, scopeOfTheContainingExpression));
}
}
}
}
if (escapeTo == scopeOfTheContainingExpression)
{
// cannot fail. common case.
return true;
}
if (!argsOpt.IsDefault)
{
moreArguments:
for (var argIndex = 0; argIndex < argsOpt.Length; argIndex++)
{
// check val escape of all arguments
var argument = argsOpt[argIndex];
if (argument.Kind == BoundKind.ArgListOperator)
{
Debug.Assert(argIndex == argsOpt.Length - 1, "vararg must be the last");
var argList = (BoundArgListOperator)argument;
// unwrap varargs and process as more arguments
argsOpt = argList.Arguments;
parameters = ImmutableArray<ParameterSymbol>.Empty;
argsToParamsOpt = default;
goto moreArguments;
}
var valid = CheckValEscape(argument.Syntax, argument, scopeOfTheContainingExpression, escapeTo, false, diagnostics);
if (!valid)
{
string parameterName;
if (parameters.Length > 0)
{
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
parameterName = parameters[paramIndex].Name;
}
else
{
parameterName = "__arglist";
}
Error(diagnostics, ErrorCode.ERR_CallArgMixing, syntax, symbol, parameterName);
return false;
}
}
}
//NB: we do not care about unmatched "in" parameters here.
// They have "outer" val escape, so cannot be worse than escapeTo.
// check val escape of receiver if ref-like
if (receiverOpt?.Type?.IsRefLikeType == true)
{
return CheckValEscape(receiverOpt.Syntax, receiverOpt, scopeOfTheContainingExpression, escapeTo, false, diagnostics);
}
return true;
static bool isReceiverRefReadOnly(Symbol methodOrPropertySymbol) => methodOrPropertySymbol switch
{
MethodSymbol m => m.IsEffectivelyReadOnly,
// TODO: val escape checks should be skipped for property accesses when
// we can determine the only accessors being called are readonly.
// For now we are pessimistic and check escape if any accessor is non-readonly.
// Tracking in https://github.com/dotnet/roslyn/issues/35606
PropertySymbol p => p.GetMethod?.IsEffectivelyReadOnly != false && p.SetMethod?.IsEffectivelyReadOnly != false,
_ => throw ExceptionUtilities.UnexpectedValue(methodOrPropertySymbol)
};
}
/// <summary>
/// Gets "effective" ref kind of an argument.
/// If the ref kind is 'in', marks that that corresponding parameter was matched with a value
/// We need that to detect when there were optional 'in' parameters for which values were not supplied.
///
/// NOTE: Generally we know if a formal argument is passed as ref/out/in by looking at the call site.
/// However, 'in' may also be passed as an ordinary val argument so we need to take a look at corresponding parameter, if such exists.
/// There are cases like params/vararg, when a corresponding parameter may not exist, then val cannot become 'in'.
/// </summary>
private static RefKind GetEffectiveRefKindAndMarkMatchedInParameter(
int argIndex,
ImmutableArray<RefKind> argRefKindsOpt,
ImmutableArray<ParameterSymbol> parameters,
ImmutableArray<int> argsToParamsOpt,
ref ArrayBuilder<bool> inParametersMatchedWithArgs)
{
var effectiveRefKind = argRefKindsOpt.IsDefault ? RefKind.None : argRefKindsOpt[argIndex];
if ((effectiveRefKind == RefKind.None || effectiveRefKind == RefKind.In) && argIndex < parameters.Length)
{
var paramIndex = argsToParamsOpt.IsDefault ? argIndex : argsToParamsOpt[argIndex];
if (parameters[paramIndex].RefKind == RefKind.In)
{
effectiveRefKind = RefKind.In;
inParametersMatchedWithArgs = inParametersMatchedWithArgs ?? ArrayBuilder<bool>.GetInstance(parameters.Length, fillWithValue: false);
inParametersMatchedWithArgs[paramIndex] = true;
}
}
return effectiveRefKind;
}
/// <summary>
/// Gets a "in" parameter for which there is no argument supplied, if such exists.
/// That indicates an optional "in" parameter. We treat it as an RValue passed by reference via a temporary.
/// The effective scope of such variable is the immediately containing scope.
/// </summary>
private static ParameterSymbol TryGetunmatchedInParameterAndFreeMatchedArgs(ImmutableArray<ParameterSymbol> parameters, ref ArrayBuilder<bool> inParametersMatchedWithArgs)
{
try
{
if (!parameters.IsDefault)
{
for (int i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
if (parameter.IsParams)
{
break;
}
if (parameter.RefKind == RefKind.In &&
inParametersMatchedWithArgs?[i] != true &&
parameter.Type.IsRefLikeType == false)
{
return parameter;
}
}
}
return null;
}
finally
{
inParametersMatchedWithArgs?.Free();
// make sure noone uses it after.
inParametersMatchedWithArgs = null;
}
}
private static ErrorCode GetStandardCallEscapeError(bool checkingReceiver)
{
return checkingReceiver ? ErrorCode.ERR_EscapeCall2 : ErrorCode.ERR_EscapeCall;
}
private static void ReportReadonlyLocalError(SyntaxNode node, LocalSymbol local, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)local != null);
Debug.Assert(kind != BindValueKind.RValue);
MessageID cause;
if (local.IsForEach)
{
cause = MessageID.IDS_FOREACHLOCAL;
}
else if (local.IsUsing)
{
cause = MessageID.IDS_USINGLOCAL;
}
else if (local.IsFixed)
{
cause = MessageID.IDS_FIXEDLOCAL;
}
else
{
Error(diagnostics, GetStandardLvalueError(kind), node);
return;
}
ErrorCode[] ReadOnlyLocalErrors =
{
ErrorCode.ERR_RefReadonlyLocalCause,
ErrorCode.ERR_AssgReadonlyLocalCause,
ErrorCode.ERR_RefReadonlyLocal2Cause,
ErrorCode.ERR_AssgReadonlyLocal2Cause
};
int index = (checkingReceiver ? 2 : 0) + (RequiresRefOrOut(kind) ? 0 : 1);
Error(diagnostics, ReadOnlyLocalErrors[index], node, local, cause.Localize());
}
private static ErrorCode GetThisLvalueError(BindValueKind kind, bool isValueType)
{
switch (kind)
{
case BindValueKind.CompoundAssignment:
case BindValueKind.Assignable:
return ErrorCode.ERR_AssgReadonlyLocal;
case BindValueKind.RefOrOut:
return ErrorCode.ERR_RefReadonlyLocal;
case BindValueKind.AddressOf:
return ErrorCode.ERR_InvalidAddrOp;
case BindValueKind.IncrementDecrement:
return isValueType ? ErrorCode.ERR_AssgReadonlyLocal : ErrorCode.ERR_IncrementLvalueExpected;
case BindValueKind.RefReturn:
case BindValueKind.ReadonlyRef:
return ErrorCode.ERR_RefReturnThis;
case BindValueKind.RefAssignable:
return ErrorCode.ERR_RefLocalOrParamExpected;
}
if (RequiresReferenceToLocation(kind))
{
return ErrorCode.ERR_RefLvalueExpected;
}
throw ExceptionUtilities.UnexpectedValue(kind);
}
private static ErrorCode GetRangeLvalueError(BindValueKind kind)
{
switch (kind)
{
case BindValueKind.Assignable:
case BindValueKind.CompoundAssignment:
case BindValueKind.IncrementDecrement:
return ErrorCode.ERR_QueryRangeVariableReadOnly;
case BindValueKind.AddressOf:
return ErrorCode.ERR_InvalidAddrOp;
case BindValueKind.RefReturn:
case BindValueKind.ReadonlyRef:
return ErrorCode.ERR_RefReturnRangeVariable;
case BindValueKind.RefAssignable:
return ErrorCode.ERR_RefLocalOrParamExpected;
}
if (RequiresReferenceToLocation(kind))
{
return ErrorCode.ERR_QueryOutRefRangeVariable;
}
throw ExceptionUtilities.UnexpectedValue(kind);
}
private static ErrorCode GetMethodGroupOrFunctionPointerLvalueError(BindValueKind valueKind)
{
if (RequiresReferenceToLocation(valueKind))
{
return ErrorCode.ERR_RefReadonlyLocalCause;
}
// Cannot assign to 'W' because it is a 'method group'
return ErrorCode.ERR_AssgReadonlyLocalCause;
}
private static ErrorCode GetStandardLvalueError(BindValueKind kind)
{
switch (kind)
{
case BindValueKind.CompoundAssignment:
case BindValueKind.Assignable:
return ErrorCode.ERR_AssgLvalueExpected;
case BindValueKind.AddressOf:
return ErrorCode.ERR_InvalidAddrOp;
case BindValueKind.IncrementDecrement:
return ErrorCode.ERR_IncrementLvalueExpected;
case BindValueKind.FixedReceiver:
return ErrorCode.ERR_FixedNeedsLvalue;
case BindValueKind.RefReturn:
case BindValueKind.ReadonlyRef:
return ErrorCode.ERR_RefReturnLvalueExpected;
case BindValueKind.RefAssignable:
return ErrorCode.ERR_RefLocalOrParamExpected;
}
if (RequiresReferenceToLocation(kind))
{
return ErrorCode.ERR_RefLvalueExpected;
}
throw ExceptionUtilities.UnexpectedValue(kind);
}
private static ErrorCode GetStandardRValueRefEscapeError(uint escapeTo)
{
if (escapeTo == Binder.ExternalScope)
{
return ErrorCode.ERR_RefReturnLvalueExpected;
}
return ErrorCode.ERR_EscapeOther;
}
private static void ReportReadOnlyFieldError(FieldSymbol field, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)field != null);
Debug.Assert(RequiresAssignableVariable(kind));
Debug.Assert(field.Type != (object)null);
// It's clearer to say that the address can't be taken than to say that the field can't be modified
// (even though the latter message gives more explanation of why).
if (kind == BindValueKind.AddressOf)
{
Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node);
return;
}
ErrorCode[] ReadOnlyErrors =
{
ErrorCode.ERR_RefReturnReadonly,
ErrorCode.ERR_RefReadonly,
ErrorCode.ERR_AssgReadonly,
ErrorCode.ERR_RefReturnReadonlyStatic,
ErrorCode.ERR_RefReadonlyStatic,
ErrorCode.ERR_AssgReadonlyStatic,
ErrorCode.ERR_RefReturnReadonly2,
ErrorCode.ERR_RefReadonly2,
ErrorCode.ERR_AssgReadonly2,
ErrorCode.ERR_RefReturnReadonlyStatic2,
ErrorCode.ERR_RefReadonlyStatic2,
ErrorCode.ERR_AssgReadonlyStatic2
};
int index = (checkingReceiver ? 6 : 0) + (field.IsStatic ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2));
if (checkingReceiver)
{
Error(diagnostics, ReadOnlyErrors[index], node, field);
}
else
{
Error(diagnostics, ReadOnlyErrors[index], node);
}
}
private static void ReportReadOnlyError(Symbol symbol, SyntaxNode node, BindValueKind kind, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)symbol != null);
Debug.Assert(RequiresAssignableVariable(kind));
// It's clearer to say that the address can't be taken than to say that the parameter can't be modified
// (even though the latter message gives more explanation of why).
if (kind == BindValueKind.AddressOf)
{
Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, node);
return;
}
var symbolKind = symbol.Kind.Localize();
ErrorCode[] ReadOnlyErrors =
{
ErrorCode.ERR_RefReturnReadonlyNotField,
ErrorCode.ERR_RefReadonlyNotField,
ErrorCode.ERR_AssignReadonlyNotField,
ErrorCode.ERR_RefReturnReadonlyNotField2,
ErrorCode.ERR_RefReadonlyNotField2,
ErrorCode.ERR_AssignReadonlyNotField2,
};
int index = (checkingReceiver ? 3 : 0) + (kind == BindValueKind.RefReturn ? 0 : (RequiresRefOrOut(kind) ? 1 : 2));
Error(diagnostics, ReadOnlyErrors[index], node, symbolKind, symbol);
}
/// <summary>
/// Checks whether given expression can escape from the current scope to the <paramref name="escapeTo"/>
/// In a case if it cannot a bad expression is returned and diagnostics is produced.
/// </summary>
internal BoundExpression ValidateEscape(BoundExpression expr, uint escapeTo, bool isByRef, BindingDiagnosticBag diagnostics)
{
if (isByRef)
{
if (CheckRefEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return expr;
}
}
else
{
if (CheckValEscape(expr.Syntax, expr, this.LocalScopeDepth, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return expr;
}
}
return ToBadExpression(expr);
}
/// <summary>
/// Computes the widest scope depth to which the given expression can escape by reference.
///
/// NOTE: in a case if expression cannot be passed by an alias (RValue and similar), the ref-escape is scopeOfTheContainingExpression
/// There are few cases where RValues are permitted to be passed by reference which implies that a temporary local proxy is passed instead.
/// We reflect such behavior by constraining the escape value to the narrowest scope possible.
/// </summary>
internal static uint GetRefEscape(BoundExpression expr, uint scopeOfTheContainingExpression)
{
// cannot infer anything from errors
if (expr.HasAnyErrors)
{
return Binder.ExternalScope;
}
// cannot infer anything from Void (broken code)
if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void)
{
return Binder.ExternalScope;
}
// constants/literals cannot ref-escape current scope
if (expr.ConstantValue != null)
{
return scopeOfTheContainingExpression;
}
// cover case that cannot refer to local state
// otherwise default to current scope (RValues, etc)
switch (expr.Kind)
{
case BoundKind.ArrayAccess:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
// array elements and pointer dereferencing are readwrite variables
return Binder.ExternalScope;
case BoundKind.RefValueOperator:
// The undocumented __refvalue(tr, T) expression results in an lvalue of type T.
// for compat reasons it is not ref-returnable (since TypedReference is not val-returnable)
// it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level)
return Binder.TopLevelScope;
case BoundKind.DiscardExpression:
// same as write-only byval local
break;
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
// dynamic expressions can be read and written to
// can even be passed by reference (which is implemented via a temp)
// it is not valid to escape them by reference though, so treat them as RValues here
break;
case BoundKind.Parameter:
var parameter = ((BoundParameter)expr).ParameterSymbol;
// byval parameters can escape to method's top level. Others can escape further.
// NOTE: "method" here means nearest containing method, lambda or local function.
return parameter.RefKind == RefKind.None ? Binder.TopLevelScope : Binder.ExternalScope;
case BoundKind.Local:
return ((BoundLocal)expr).LocalSymbol.RefEscapeScope;
case BoundKind.ThisReference:
var thisref = (BoundThisReference)expr;
// "this" is an RValue, unless in a struct.
if (!thisref.Type.IsValueType)
{
break;
}
//"this" is not returnable by reference in a struct.
// can ref escape to any other level
return Binder.TopLevelScope;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
if (conditional.IsRef)
{
// ref conditional defers to its operands
return Math.Max(GetRefEscape(conditional.Consequence, scopeOfTheContainingExpression),
GetRefEscape(conditional.Alternative, scopeOfTheContainingExpression));
}
// otherwise it is an RValue
break;
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
var fieldSymbol = fieldAccess.FieldSymbol;
// fields that are static or belong to reference types can ref escape anywhere
if (fieldSymbol.IsStatic || fieldSymbol.ContainingType.IsReferenceType)
{
return Binder.ExternalScope;
}
// for other fields defer to the receiver.
return GetRefEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression);
case BoundKind.EventAccess:
var eventAccess = (BoundEventAccess)expr;
if (!eventAccess.IsUsableAsField)
{
// not field-like events are RValues
break;
}
var eventSymbol = eventAccess.EventSymbol;
// field-like events that are static or belong to reference types can ref escape anywhere
if (eventSymbol.IsStatic || eventSymbol.ContainingType.IsReferenceType)
{
return Binder.ExternalScope;
}
// for other events defer to the receiver.
return GetRefEscape(eventAccess.ReceiverOpt, scopeOfTheContainingExpression);
case BoundKind.Call:
var call = (BoundCall)expr;
var methodSymbol = call.Method;
if (methodSymbol.RefKind == RefKind.None)
{
break;
}
return GetInvocationEscapeScope(
call.Method,
call.ReceiverOpt,
methodSymbol.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.FunctionPointerInvocation:
var ptrInvocation = (BoundFunctionPointerInvocation)expr;
methodSymbol = ptrInvocation.FunctionPointer.Signature;
if (methodSymbol.RefKind == RefKind.None)
{
break;
}
return GetInvocationEscapeScope(
methodSymbol,
receiverOpt: null,
methodSymbol.Parameters,
ptrInvocation.Arguments,
ptrInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
return GetInvocationEscapeScope(
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
// not passing any arguments/parameters
return GetInvocationEscapeScope(
propertyAccess.PropertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
scopeOfTheContainingExpression,
isRefEscape: true);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
if (!assignment.IsRef)
{
// non-ref assignments are RValues
break;
}
return GetRefEscape(assignment.Left, scopeOfTheContainingExpression);
}
// At this point we should have covered all the possible cases for anything that is not a strict RValue.
return scopeOfTheContainingExpression;
}
/// <summary>
/// A counterpart to the GetRefEscape, which validates if given escape demand can be met by the expression.
/// The result indicates whether the escape is possible.
/// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure.
/// </summary>
internal static bool CheckRefEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter());
if (escapeTo >= escapeFrom)
{
// escaping to same or narrower scope is ok.
return true;
}
if (expr.HasAnyErrors)
{
// already an error
return true;
}
// void references cannot escape (error should be reported somewhere)
if (expr.Type?.GetSpecialTypeSafe() == SpecialType.System_Void)
{
return true;
}
// references to constants/literals cannot escape higher.
if (expr.ConstantValue != null)
{
Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node);
return false;
}
switch (expr.Kind)
{
case BoundKind.ArrayAccess:
case BoundKind.PointerIndirectionOperator:
case BoundKind.PointerElementAccess:
// array elements and pointer dereferencing are readwrite variables
return true;
case BoundKind.RefValueOperator:
// The undocumented __refvalue(tr, T) expression results in an lvalue of type T.
// for compat reasons it is not ref-returnable (since TypedReference is not val-returnable)
if (escapeTo == Binder.ExternalScope)
{
break;
}
// it can, however, ref-escape to any other level (since TypedReference can val-escape to any other level)
return true;
case BoundKind.DiscardExpression:
// same as write-only byval local
break;
case BoundKind.DynamicMemberAccess:
case BoundKind.DynamicIndexerAccess:
// dynamic expressions can be read and written to
// can even be passed by reference (which is implemented via a temp)
// it is not valid to escape them by reference though.
break;
case BoundKind.Parameter:
var parameter = (BoundParameter)expr;
return CheckParameterRefEscape(node, parameter, escapeTo, checkingReceiver, diagnostics);
case BoundKind.Local:
var local = (BoundLocal)expr;
return CheckLocalRefEscape(node, local, escapeTo, checkingReceiver, diagnostics);
case BoundKind.ThisReference:
var thisref = (BoundThisReference)expr;
// "this" is an RValue, unless in a struct.
if (!thisref.Type.IsValueType)
{
break;
}
//"this" is not returnable by reference in a struct.
if (escapeTo == Binder.ExternalScope)
{
Error(diagnostics, ErrorCode.ERR_RefReturnStructThis, node, ThisParameterSymbol.SymbolName);
return false;
}
// can ref escape to any other level
return true;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
if (conditional.IsRef)
{
return CheckRefEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckRefEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
}
// report standard lvalue error
break;
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
return CheckFieldRefEscape(node, fieldAccess, escapeFrom, escapeTo, diagnostics);
case BoundKind.EventAccess:
var eventAccess = (BoundEventAccess)expr;
if (!eventAccess.IsUsableAsField)
{
// not field-like events are RValues
break;
}
return CheckFieldLikeEventRefEscape(node, eventAccess, escapeFrom, escapeTo, diagnostics);
case BoundKind.Call:
var call = (BoundCall)expr;
var methodSymbol = call.Method;
if (methodSymbol.RefKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
call.Syntax,
methodSymbol,
call.ReceiverOpt,
methodSymbol.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
if (indexerSymbol.RefKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
indexerAccess.Syntax,
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
RefKind refKind;
ImmutableArray<ParameterSymbol> parameters;
switch (patternIndexer.PatternSymbol)
{
case PropertySymbol p:
refKind = p.RefKind;
parameters = p.Parameters;
break;
case MethodSymbol m:
refKind = m.RefKind;
parameters = m.Parameters;
break;
default:
throw ExceptionUtilities.Unreachable;
}
if (refKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
patternIndexer.Syntax,
patternIndexer.PatternSymbol,
patternIndexer.Receiver,
parameters,
ImmutableArray.Create<BoundExpression>(patternIndexer.Argument),
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.FunctionPointerInvocation:
var functionPointerInvocation = (BoundFunctionPointerInvocation)expr;
FunctionPointerMethodSymbol signature = functionPointerInvocation.FunctionPointer.Signature;
if (signature.RefKind == RefKind.None)
{
break;
}
return CheckInvocationEscape(
functionPointerInvocation.Syntax,
signature,
functionPointerInvocation.InvokedExpression,
signature.Parameters,
functionPointerInvocation.Arguments,
functionPointerInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
var propertySymbol = propertyAccess.PropertySymbol;
if (propertySymbol.RefKind == RefKind.None)
{
break;
}
// not passing any arguments/parameters
return CheckInvocationEscape(
propertyAccess.Syntax,
propertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: true);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
// Only ref-assignments can be LValues
if (!assignment.IsRef)
{
break;
}
return CheckRefEscape(
node,
assignment.Left,
escapeFrom,
escapeTo,
checkingReceiver: false,
diagnostics);
}
// At this point we should have covered all the possible cases for anything that is not a strict RValue.
Error(diagnostics, GetStandardRValueRefEscapeError(escapeTo), node);
return false;
}
internal static uint GetBroadestValEscape(BoundTupleExpression expr, uint scopeOfTheContainingExpression)
{
uint broadest = scopeOfTheContainingExpression;
foreach (var element in expr.Arguments)
{
uint valEscape;
if (element is BoundTupleExpression te)
{
valEscape = GetBroadestValEscape(te, scopeOfTheContainingExpression);
}
else
{
valEscape = GetValEscape(element, scopeOfTheContainingExpression);
}
broadest = Math.Min(broadest, valEscape);
}
return broadest;
}
/// <summary>
/// Computes the widest scope depth to which the given expression can escape by value.
///
/// NOTE: unless the type of expression is ref-like, the result is Binder.ExternalScope since ordinary values can always be returned from methods.
/// </summary>
internal static uint GetValEscape(BoundExpression expr, uint scopeOfTheContainingExpression)
{
// cannot infer anything from errors
if (expr.HasAnyErrors)
{
return Binder.ExternalScope;
}
// constants/literals cannot refer to local state
if (expr.ConstantValue != null)
{
return Binder.ExternalScope;
}
// to have local-referring values an expression must have a ref-like type
if (expr.Type?.IsRefLikeType != true)
{
return Binder.ExternalScope;
}
// cover case that can refer to local state
// otherwise default to ExternalScope (ordinary values)
switch (expr.Kind)
{
case BoundKind.DefaultLiteral:
case BoundKind.DefaultExpression:
case BoundKind.Parameter:
case BoundKind.ThisReference:
// always returnable
return Binder.ExternalScope;
case BoundKind.TupleLiteral:
case BoundKind.ConvertedTupleLiteral:
var tupleLiteral = (BoundTupleExpression)expr;
return GetTupleValEscape(tupleLiteral.Arguments, scopeOfTheContainingExpression);
case BoundKind.MakeRefOperator:
case BoundKind.RefValueOperator:
// for compat reasons
// NB: it also means can`t assign stackalloc spans to a __refvalue
// we are ok with that.
return Binder.ExternalScope;
case BoundKind.DiscardExpression:
// same as uninitialized local
return Binder.ExternalScope;
case BoundKind.DeconstructValuePlaceholder:
return ((BoundDeconstructValuePlaceholder)expr).ValEscape;
case BoundKind.Local:
return ((BoundLocal)expr).LocalSymbol.ValEscapeScope;
case BoundKind.StackAllocArrayCreation:
case BoundKind.ConvertedStackAllocExpression:
return Binder.TopLevelScope;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expr;
var consEscape = GetValEscape(conditional.Consequence, scopeOfTheContainingExpression);
if (conditional.IsRef)
{
// ref conditional defers to one operand.
// the other one is the same or we will be reporting errors anyways.
return consEscape;
}
// val conditional gets narrowest of its operands
return Math.Max(consEscape,
GetValEscape(conditional.Alternative, scopeOfTheContainingExpression));
case BoundKind.NullCoalescingOperator:
var coalescingOp = (BoundNullCoalescingOperator)expr;
return Math.Max(GetValEscape(coalescingOp.LeftOperand, scopeOfTheContainingExpression),
GetValEscape(coalescingOp.RightOperand, scopeOfTheContainingExpression));
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
var fieldSymbol = fieldAccess.FieldSymbol;
if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType)
{
// Already an error state.
return Binder.ExternalScope;
}
// for ref-like fields defer to the receiver.
return GetValEscape(fieldAccess.ReceiverOpt, scopeOfTheContainingExpression);
case BoundKind.Call:
var call = (BoundCall)expr;
return GetInvocationEscapeScope(
call.Method,
call.ReceiverOpt,
call.Method.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.FunctionPointerInvocation:
var ptrInvocation = (BoundFunctionPointerInvocation)expr;
var ptrSymbol = ptrInvocation.FunctionPointer.Signature;
return GetInvocationEscapeScope(
ptrSymbol,
receiverOpt: null,
ptrSymbol.Parameters,
ptrInvocation.Arguments,
ptrInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
return GetInvocationEscapeScope(
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
var parameters = patternIndexer.PatternSymbol switch
{
PropertySymbol p => p.Parameters,
MethodSymbol m => m.Parameters,
_ => throw ExceptionUtilities.UnexpectedValue(patternIndexer.PatternSymbol)
};
return GetInvocationEscapeScope(
patternIndexer.PatternSymbol,
patternIndexer.Receiver,
parameters,
default,
default,
default,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
// not passing any arguments/parameters
return GetInvocationEscapeScope(
propertyAccess.PropertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
scopeOfTheContainingExpression,
isRefEscape: false);
case BoundKind.ObjectCreationExpression:
var objectCreation = (BoundObjectCreationExpression)expr;
var constructorSymbol = objectCreation.Constructor;
var escape = GetInvocationEscapeScope(
constructorSymbol,
null,
constructorSymbol.Parameters,
objectCreation.Arguments,
objectCreation.ArgumentRefKindsOpt,
objectCreation.ArgsToParamsOpt,
scopeOfTheContainingExpression,
isRefEscape: false);
var initializerOpt = objectCreation.InitializerExpressionOpt;
if (initializerOpt != null)
{
escape = Math.Max(escape, GetValEscape(initializerOpt, scopeOfTheContainingExpression));
}
return escape;
case BoundKind.WithExpression:
var withExpression = (BoundWithExpression)expr;
return Math.Max(GetValEscape(withExpression.Receiver, scopeOfTheContainingExpression),
GetValEscape(withExpression.InitializerExpression, scopeOfTheContainingExpression));
case BoundKind.UnaryOperator:
return GetValEscape(((BoundUnaryOperator)expr).Operand, scopeOfTheContainingExpression);
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected");
if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler)
{
return GetInterpolatedStringHandlerConversionEscapeScope((BoundInterpolatedString)conversion.Operand, scopeOfTheContainingExpression);
}
return GetValEscape(conversion.Operand, scopeOfTheContainingExpression);
case BoundKind.AssignmentOperator:
return GetValEscape(((BoundAssignmentOperator)expr).Right, scopeOfTheContainingExpression);
case BoundKind.IncrementOperator:
return GetValEscape(((BoundIncrementOperator)expr).Operand, scopeOfTheContainingExpression);
case BoundKind.CompoundAssignmentOperator:
var compound = (BoundCompoundAssignmentOperator)expr;
return Math.Max(GetValEscape(compound.Left, scopeOfTheContainingExpression),
GetValEscape(compound.Right, scopeOfTheContainingExpression));
case BoundKind.BinaryOperator:
var binary = (BoundBinaryOperator)expr;
return Math.Max(GetValEscape(binary.Left, scopeOfTheContainingExpression),
GetValEscape(binary.Right, scopeOfTheContainingExpression));
case BoundKind.UserDefinedConditionalLogicalOperator:
var uo = (BoundUserDefinedConditionalLogicalOperator)expr;
return Math.Max(GetValEscape(uo.Left, scopeOfTheContainingExpression),
GetValEscape(uo.Right, scopeOfTheContainingExpression));
case BoundKind.QueryClause:
return GetValEscape(((BoundQueryClause)expr).Value, scopeOfTheContainingExpression);
case BoundKind.RangeVariable:
return GetValEscape(((BoundRangeVariable)expr).Value, scopeOfTheContainingExpression);
case BoundKind.ObjectInitializerExpression:
var initExpr = (BoundObjectInitializerExpression)expr;
return GetValEscapeOfObjectInitializer(initExpr, scopeOfTheContainingExpression);
case BoundKind.CollectionInitializerExpression:
var colExpr = (BoundCollectionInitializerExpression)expr;
return GetValEscape(colExpr.Initializers, scopeOfTheContainingExpression);
case BoundKind.CollectionElementInitializer:
var colElement = (BoundCollectionElementInitializer)expr;
return GetValEscape(colElement.Arguments, scopeOfTheContainingExpression);
case BoundKind.ObjectInitializerMember:
// this node generally makes no sense outside of the context of containing initializer
// however binder uses it as a placeholder when binding assignments inside an object initializer
// just say it does not escape anywhere, so that we do not get false errors.
return scopeOfTheContainingExpression;
case BoundKind.ImplicitReceiver:
case BoundKind.ObjectOrCollectionValuePlaceholder:
// binder uses this as a placeholder when binding members inside an object initializer
// just say it does not escape anywhere, so that we do not get false errors.
return scopeOfTheContainingExpression;
case BoundKind.InterpolatedStringHandlerPlaceholder:
// The handler placeholder cannot escape out of the current expression, as it's a compiler-synthesized
// location.
return scopeOfTheContainingExpression;
case BoundKind.InterpolatedStringArgumentPlaceholder:
// We saved off the safe-to-escape of the argument when we did binding
return ((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape;
case BoundKind.DisposableValuePlaceholder:
// Disposable value placeholder is only ever used to lookup a pattern dispose method
// then immediately discarded. The actual expression will be generated during lowering
return scopeOfTheContainingExpression;
case BoundKind.AwaitableValuePlaceholder:
return ((BoundAwaitableValuePlaceholder)expr).ValEscape;
case BoundKind.PointerElementAccess:
case BoundKind.PointerIndirectionOperator:
// Unsafe code will always be allowed to escape.
return Binder.ExternalScope;
case BoundKind.AsOperator:
case BoundKind.AwaitExpression:
case BoundKind.ConditionalAccess:
case BoundKind.ArrayAccess:
// only possible in error cases (if possible at all)
return scopeOfTheContainingExpression;
case BoundKind.ConvertedSwitchExpression:
case BoundKind.UnconvertedSwitchExpression:
var switchExpr = (BoundSwitchExpression)expr;
return GetValEscape(switchExpr.SwitchArms.SelectAsArray(a => a.Value), scopeOfTheContainingExpression);
default:
// in error situations some unexpected nodes could make here
// returning "scopeOfTheContainingExpression" seems safer than throwing.
// we will still assert to make sure that all nodes are accounted for.
Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type");
return scopeOfTheContainingExpression;
}
}
private static uint GetTupleValEscape(ImmutableArray<BoundExpression> elements, uint scopeOfTheContainingExpression)
{
uint narrowestScope = scopeOfTheContainingExpression;
foreach (var element in elements)
{
narrowestScope = Math.Max(narrowestScope, GetValEscape(element, scopeOfTheContainingExpression));
}
return narrowestScope;
}
private static uint GetValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint scopeOfTheContainingExpression)
{
var result = Binder.ExternalScope;
foreach (var expression in initExpr.Initializers)
{
if (expression.Kind == BoundKind.AssignmentOperator)
{
var assignment = (BoundAssignmentOperator)expression;
result = Math.Max(result, GetValEscape(assignment.Right, scopeOfTheContainingExpression));
var left = (BoundObjectInitializerMember)assignment.Left;
result = Math.Max(result, GetValEscape(left.Arguments, scopeOfTheContainingExpression));
}
else
{
result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression));
}
}
return result;
}
private static uint GetValEscape(ImmutableArray<BoundExpression> expressions, uint scopeOfTheContainingExpression)
{
var result = Binder.ExternalScope;
foreach (var expression in expressions)
{
result = Math.Max(result, GetValEscape(expression, scopeOfTheContainingExpression));
}
return result;
}
/// <summary>
/// A counterpart to the GetValEscape, which validates if given escape demand can be met by the expression.
/// The result indicates whether the escape is possible.
/// Additionally, the method emits diagnostics (possibly more than one, recursively) that would help identify the cause for the failure.
/// </summary>
internal static bool CheckValEscape(SyntaxNode node, BoundExpression expr, uint escapeFrom, uint escapeTo, bool checkingReceiver, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!checkingReceiver || expr.Type.IsValueType || expr.Type.IsTypeParameter());
if (escapeTo >= escapeFrom)
{
// escaping to same or narrower scope is ok.
return true;
}
// cannot infer anything from errors
if (expr.HasAnyErrors)
{
return true;
}
// constants/literals cannot refer to local state
if (expr.ConstantValue != null)
{
return true;
}
// to have local-referring values an expression must have a ref-like type
if (expr.Type?.IsRefLikeType != true)
{
return true;
}
switch (expr.Kind)
{
case BoundKind.DefaultLiteral:
case BoundKind.DefaultExpression:
case BoundKind.Parameter:
case BoundKind.ThisReference:
// always returnable
return true;
case BoundKind.TupleLiteral:
case BoundKind.ConvertedTupleLiteral:
var tupleLiteral = (BoundTupleExpression)expr;
return CheckTupleValEscape(tupleLiteral.Arguments, escapeFrom, escapeTo, diagnostics);
case BoundKind.MakeRefOperator:
case BoundKind.RefValueOperator:
// for compat reasons
return true;
case BoundKind.DiscardExpression:
// same as uninitialized local
return true;
case BoundKind.DeconstructValuePlaceholder:
if (((BoundDeconstructValuePlaceholder)expr).ValEscape > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax);
return false;
}
return true;
case BoundKind.AwaitableValuePlaceholder:
if (((BoundAwaitableValuePlaceholder)expr).ValEscape > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax);
return false;
}
return true;
case BoundKind.InterpolatedStringArgumentPlaceholder:
if (((BoundInterpolatedStringArgumentPlaceholder)expr).ValSafeToEscape > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, expr.Syntax);
return false;
}
return true;
case BoundKind.Local:
var localSymbol = ((BoundLocal)expr).LocalSymbol;
if (localSymbol.ValEscapeScope > escapeTo)
{
Error(diagnostics, ErrorCode.ERR_EscapeLocal, node, localSymbol);
return false;
}
return true;
case BoundKind.StackAllocArrayCreation:
case BoundKind.ConvertedStackAllocExpression:
if (escapeTo < Binder.TopLevelScope)
{
Error(diagnostics, ErrorCode.ERR_EscapeStackAlloc, node, expr.Type);
return false;
}
return true;
case BoundKind.UnconvertedConditionalOperator:
{
var conditional = (BoundUnconvertedConditionalOperator)expr;
return
CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
}
case BoundKind.ConditionalOperator:
{
var conditional = (BoundConditionalOperator)expr;
var consValid = CheckValEscape(conditional.Consequence.Syntax, conditional.Consequence, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
if (!consValid || conditional.IsRef)
{
// ref conditional defers to one operand.
// the other one is the same or we will be reporting errors anyways.
return consValid;
}
return CheckValEscape(conditional.Alternative.Syntax, conditional.Alternative, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
}
case BoundKind.NullCoalescingOperator:
var coalescingOp = (BoundNullCoalescingOperator)expr;
return CheckValEscape(coalescingOp.LeftOperand.Syntax, coalescingOp.LeftOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics) &&
CheckValEscape(coalescingOp.RightOperand.Syntax, coalescingOp.RightOperand, escapeFrom, escapeTo, checkingReceiver, diagnostics);
case BoundKind.FieldAccess:
var fieldAccess = (BoundFieldAccess)expr;
var fieldSymbol = fieldAccess.FieldSymbol;
if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsRefLikeType)
{
// Already an error state.
return true;
}
// for ref-like fields defer to the receiver.
return CheckValEscape(node, fieldAccess.ReceiverOpt, escapeFrom, escapeTo, true, diagnostics);
case BoundKind.Call:
var call = (BoundCall)expr;
var methodSymbol = call.Method;
return CheckInvocationEscape(
call.Syntax,
methodSymbol,
call.ReceiverOpt,
methodSymbol.Parameters,
call.Arguments,
call.ArgumentRefKindsOpt,
call.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.FunctionPointerInvocation:
var ptrInvocation = (BoundFunctionPointerInvocation)expr;
var ptrSymbol = ptrInvocation.FunctionPointer.Signature;
return CheckInvocationEscape(
ptrInvocation.Syntax,
ptrSymbol,
receiverOpt: null,
ptrSymbol.Parameters,
ptrInvocation.Arguments,
ptrInvocation.ArgumentRefKindsOpt,
argsToParamsOpt: default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.IndexerAccess:
var indexerAccess = (BoundIndexerAccess)expr;
var indexerSymbol = indexerAccess.Indexer;
return CheckInvocationEscape(
indexerAccess.Syntax,
indexerSymbol,
indexerAccess.ReceiverOpt,
indexerSymbol.Parameters,
indexerAccess.Arguments,
indexerAccess.ArgumentRefKindsOpt,
indexerAccess.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.IndexOrRangePatternIndexerAccess:
var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr;
var patternSymbol = patternIndexer.PatternSymbol;
var parameters = patternSymbol switch
{
PropertySymbol p => p.Parameters,
MethodSymbol m => m.Parameters,
_ => throw ExceptionUtilities.Unreachable,
};
return CheckInvocationEscape(
patternIndexer.Syntax,
patternSymbol,
patternIndexer.Receiver,
parameters,
ImmutableArray.Create(patternIndexer.Argument),
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.PropertyAccess:
var propertyAccess = (BoundPropertyAccess)expr;
// not passing any arguments/parameters
return CheckInvocationEscape(
propertyAccess.Syntax,
propertyAccess.PropertySymbol,
propertyAccess.ReceiverOpt,
default,
default,
default,
default,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
case BoundKind.ObjectCreationExpression:
{
var objectCreation = (BoundObjectCreationExpression)expr;
var constructorSymbol = objectCreation.Constructor;
var escape = CheckInvocationEscape(
objectCreation.Syntax,
constructorSymbol,
null,
constructorSymbol.Parameters,
objectCreation.Arguments,
objectCreation.ArgumentRefKindsOpt,
objectCreation.ArgsToParamsOpt,
checkingReceiver,
escapeFrom,
escapeTo,
diagnostics,
isRefEscape: false);
var initializerExpr = objectCreation.InitializerExpressionOpt;
if (initializerExpr != null)
{
escape = escape &&
CheckValEscape(
initializerExpr.Syntax,
initializerExpr,
escapeFrom,
escapeTo,
checkingReceiver: false,
diagnostics: diagnostics);
}
return escape;
}
case BoundKind.WithExpression:
{
var withExpr = (BoundWithExpression)expr;
var escape = CheckValEscape(node, withExpr.Receiver, escapeFrom, escapeTo, checkingReceiver: false, diagnostics);
var initializerExpr = withExpr.InitializerExpression;
escape = escape && CheckValEscape(initializerExpr.Syntax, initializerExpr, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
return escape;
}
case BoundKind.UnaryOperator:
var unary = (BoundUnaryOperator)expr;
return CheckValEscape(node, unary.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.Conversion:
var conversion = (BoundConversion)expr;
Debug.Assert(conversion.ConversionKind != ConversionKind.StackAllocToSpanType, "StackAllocToSpanType unexpected");
if (conversion.ConversionKind == ConversionKind.InterpolatedStringHandler)
{
return CheckInterpolatedStringHandlerConversionEscape((BoundInterpolatedString)conversion.Operand, escapeFrom, escapeTo, diagnostics);
}
return CheckValEscape(node, conversion.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expr;
return CheckValEscape(node, assignment.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.IncrementOperator:
var increment = (BoundIncrementOperator)expr;
return CheckValEscape(node, increment.Operand, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.CompoundAssignmentOperator:
var compound = (BoundCompoundAssignmentOperator)expr;
return CheckValEscape(compound.Left.Syntax, compound.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(compound.Right.Syntax, compound.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.BinaryOperator:
var binary = (BoundBinaryOperator)expr;
return CheckValEscape(binary.Left.Syntax, binary.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(binary.Right.Syntax, binary.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.UserDefinedConditionalLogicalOperator:
var uo = (BoundUserDefinedConditionalLogicalOperator)expr;
return CheckValEscape(uo.Left.Syntax, uo.Left, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics) &&
CheckValEscape(uo.Right.Syntax, uo.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.QueryClause:
var clauseValue = ((BoundQueryClause)expr).Value;
return CheckValEscape(clauseValue.Syntax, clauseValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.RangeVariable:
var variableValue = ((BoundRangeVariable)expr).Value;
return CheckValEscape(variableValue.Syntax, variableValue, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics);
case BoundKind.ObjectInitializerExpression:
var initExpr = (BoundObjectInitializerExpression)expr;
return CheckValEscapeOfObjectInitializer(initExpr, escapeFrom, escapeTo, diagnostics);
// this would be correct implementation for CollectionInitializerExpression
// however it is unclear if it is reachable since the initialized type must implement IEnumerable
case BoundKind.CollectionInitializerExpression:
var colExpr = (BoundCollectionInitializerExpression)expr;
return CheckValEscape(colExpr.Initializers, escapeFrom, escapeTo, diagnostics);
// this would be correct implementation for CollectionElementInitializer
// however it is unclear if it is reachable since the initialized type must implement IEnumerable
case BoundKind.CollectionElementInitializer:
var colElement = (BoundCollectionElementInitializer)expr;
return CheckValEscape(colElement.Arguments, escapeFrom, escapeTo, diagnostics);
case BoundKind.PointerElementAccess:
var accessedExpression = ((BoundPointerElementAccess)expr).Expression;
return CheckValEscape(accessedExpression.Syntax, accessedExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics);
case BoundKind.PointerIndirectionOperator:
var operandExpression = ((BoundPointerIndirectionOperator)expr).Operand;
return CheckValEscape(operandExpression.Syntax, operandExpression, escapeFrom, escapeTo, checkingReceiver, diagnostics);
case BoundKind.AsOperator:
case BoundKind.AwaitExpression:
case BoundKind.ConditionalAccess:
case BoundKind.ArrayAccess:
// only possible in error cases (if possible at all)
return false;
case BoundKind.UnconvertedSwitchExpression:
case BoundKind.ConvertedSwitchExpression:
foreach (var arm in ((BoundSwitchExpression)expr).SwitchArms)
{
var result = arm.Value;
if (!CheckValEscape(result.Syntax, result, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
return false;
}
return true;
default:
// in error situations some unexpected nodes could make here
// returning "false" seems safer than throwing.
// we will still assert to make sure that all nodes are accounted for.
Debug.Assert(false, $"{expr.Kind} expression of {expr.Type} type");
diagnostics.Add(ErrorCode.ERR_InternalError, node.Location);
return false;
#region "cannot produce ref-like values"
// case BoundKind.ThrowExpression:
// case BoundKind.ArgListOperator:
// case BoundKind.ArgList:
// case BoundKind.RefTypeOperator:
// case BoundKind.AddressOfOperator:
// case BoundKind.TypeOfOperator:
// case BoundKind.IsOperator:
// case BoundKind.SizeOfOperator:
// case BoundKind.DynamicMemberAccess:
// case BoundKind.DynamicInvocation:
// case BoundKind.NewT:
// case BoundKind.DelegateCreationExpression:
// case BoundKind.ArrayCreation:
// case BoundKind.AnonymousObjectCreationExpression:
// case BoundKind.NameOfOperator:
// case BoundKind.InterpolatedString:
// case BoundKind.StringInsert:
// case BoundKind.DynamicIndexerAccess:
// case BoundKind.Lambda:
// case BoundKind.DynamicObjectCreationExpression:
// case BoundKind.NoPiaObjectCreationExpression:
// case BoundKind.BaseReference:
// case BoundKind.Literal:
// case BoundKind.IsPatternExpression:
// case BoundKind.DeconstructionAssignmentOperator:
// case BoundKind.EventAccess:
#endregion
#region "not expression that can produce a value"
// case BoundKind.FieldEqualsValue:
// case BoundKind.PropertyEqualsValue:
// case BoundKind.ParameterEqualsValue:
// case BoundKind.NamespaceExpression:
// case BoundKind.TypeExpression:
// case BoundKind.BadStatement:
// case BoundKind.MethodDefIndex:
// case BoundKind.SourceDocumentIndex:
// case BoundKind.ArgList:
// case BoundKind.ArgListOperator:
// case BoundKind.Block:
// case BoundKind.Scope:
// case BoundKind.NoOpStatement:
// case BoundKind.ReturnStatement:
// case BoundKind.YieldReturnStatement:
// case BoundKind.YieldBreakStatement:
// case BoundKind.ThrowStatement:
// case BoundKind.ExpressionStatement:
// case BoundKind.SwitchStatement:
// case BoundKind.SwitchSection:
// case BoundKind.SwitchLabel:
// case BoundKind.BreakStatement:
// case BoundKind.LocalFunctionStatement:
// case BoundKind.ContinueStatement:
// case BoundKind.PatternSwitchStatement:
// case BoundKind.PatternSwitchSection:
// case BoundKind.PatternSwitchLabel:
// case BoundKind.IfStatement:
// case BoundKind.DoStatement:
// case BoundKind.WhileStatement:
// case BoundKind.ForStatement:
// case BoundKind.ForEachStatement:
// case BoundKind.ForEachDeconstructStep:
// case BoundKind.UsingStatement:
// case BoundKind.FixedStatement:
// case BoundKind.LockStatement:
// case BoundKind.TryStatement:
// case BoundKind.CatchBlock:
// case BoundKind.LabelStatement:
// case BoundKind.GotoStatement:
// case BoundKind.LabeledStatement:
// case BoundKind.Label:
// case BoundKind.StatementList:
// case BoundKind.ConditionalGoto:
// case BoundKind.LocalDeclaration:
// case BoundKind.MultipleLocalDeclarations:
// case BoundKind.ArrayInitialization:
// case BoundKind.AnonymousPropertyDeclaration:
// case BoundKind.MethodGroup:
// case BoundKind.PropertyGroup:
// case BoundKind.EventAssignmentOperator:
// case BoundKind.Attribute:
// case BoundKind.FixedLocalCollectionInitializer:
// case BoundKind.DynamicObjectInitializerMember:
// case BoundKind.DynamicCollectionElementInitializer:
// case BoundKind.ImplicitReceiver:
// case BoundKind.FieldInitializer:
// case BoundKind.GlobalStatementInitializer:
// case BoundKind.TypeOrInstanceInitializers:
// case BoundKind.DeclarationPattern:
// case BoundKind.ConstantPattern:
// case BoundKind.WildcardPattern:
#endregion
#region "not found as an operand in no-error unlowered bound tree"
// case BoundKind.MaximumMethodDefIndex:
// case BoundKind.InstrumentationPayloadRoot:
// case BoundKind.ModuleVersionId:
// case BoundKind.ModuleVersionIdString:
// case BoundKind.Dup:
// case BoundKind.TypeOrValueExpression:
// case BoundKind.BadExpression:
// case BoundKind.ArrayLength:
// case BoundKind.MethodInfo:
// case BoundKind.FieldInfo:
// case BoundKind.SequencePoint:
// case BoundKind.SequencePointExpression:
// case BoundKind.SequencePointWithSpan:
// case BoundKind.StateMachineScope:
// case BoundKind.ConditionalReceiver:
// case BoundKind.ComplexConditionalReceiver:
// case BoundKind.PreviousSubmissionReference:
// case BoundKind.HostObjectMemberReference:
// case BoundKind.UnboundLambda:
// case BoundKind.LoweredConditionalAccess:
// case BoundKind.Sequence:
// case BoundKind.HoistedFieldAccess:
// case BoundKind.OutVariablePendingInference:
// case BoundKind.DeconstructionVariablePendingInference:
// case BoundKind.OutDeconstructVarPendingInference:
// case BoundKind.PseudoVariable:
#endregion
}
}
private static bool CheckTupleValEscape(ImmutableArray<BoundExpression> elements, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
foreach (var element in elements)
{
if (!CheckValEscape(element.Syntax, element, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
}
return true;
}
private static bool CheckValEscapeOfObjectInitializer(BoundObjectInitializerExpression initExpr, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
foreach (var expression in initExpr.Initializers)
{
if (expression.Kind == BoundKind.AssignmentOperator)
{
var assignment = (BoundAssignmentOperator)expression;
if (!CheckValEscape(expression.Syntax, assignment.Right, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
var left = (BoundObjectInitializerMember)assignment.Left;
if (!CheckValEscape(left.Arguments, escapeFrom, escapeTo, diagnostics: diagnostics))
{
return false;
}
}
else
{
if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
}
}
return true;
}
private static bool CheckValEscape(ImmutableArray<BoundExpression> expressions, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
foreach (var expression in expressions)
{
if (!CheckValEscape(expression.Syntax, expression, escapeFrom, escapeTo, checkingReceiver: false, diagnostics: diagnostics))
{
return false;
}
}
return true;
}
private static bool CheckInterpolatedStringHandlerConversionEscape(BoundInterpolatedString interpolatedString, uint escapeFrom, uint escapeTo, BindingDiagnosticBag diagnostics)
{
Debug.Assert(interpolatedString.InterpolationData is not null);
// We need to check to see if any values could potentially escape outside the max depth via the handler type.
// Consider the case where a ref-struct handler saves off the result of one call to AppendFormatted,
// and then on a subsequent call it either assigns that saved value to another ref struct with a larger
// escape, or does the opposite. In either case, we need to check.
CheckValEscape(interpolatedString.Syntax, interpolatedString.InterpolationData.GetValueOrDefault().Construction, escapeFrom, escapeTo, checkingReceiver: false, diagnostics);
foreach (var part in interpolatedString.Parts)
{
if (part is not BoundCall { Method: { Name: "AppendFormatted" } } call)
{
// Dynamic calls cannot have ref struct parameters, and AppendLiteral calls will always have literal
// string arguments and do not require us to be concerned with escape
continue;
}
// The interpolation component is always the first argument to the method, and it was not passed by name
// so there can be no reordering.
var argument = call.Arguments[0];
var success = CheckValEscape(argument.Syntax, argument, escapeFrom, escapeTo, checkingReceiver: false, diagnostics);
if (!success)
{
return false;
}
}
return true;
}
internal enum AddressKind
{
// reference may be written to
Writeable,
// reference itself will not be written to, but may be used for call, callvirt.
// for all purposes it is the same as Writeable, except when fetching an address of an array element
// where it results in a ".readonly" prefix to deal with array covariance.
Constrained,
// reference itself will not be written to, nor it will be used to modify fields.
ReadOnly,
// same as ReadOnly, but we are not supposed to get a reference to a clone
// regardless of compat settings.
ReadOnlyStrict,
}
internal static bool IsAnyReadOnly(AddressKind addressKind) => addressKind >= AddressKind.ReadOnly;
/// <summary>
/// Checks if expression directly or indirectly represents a value with its own home. In
/// such cases it is possible to get a reference without loading into a temporary.
/// </summary>
internal static bool HasHome(
BoundExpression expression,
AddressKind addressKind,
MethodSymbol method,
bool peVerifyCompatEnabled,
HashSet<LocalSymbol> stackLocalsOpt)
{
Debug.Assert(method is object);
switch (expression.Kind)
{
case BoundKind.ArrayAccess:
if (addressKind == AddressKind.ReadOnly && !expression.Type.IsValueType && peVerifyCompatEnabled)
{
// due to array covariance getting a reference may throw ArrayTypeMismatch when element is not a struct,
// passing "readonly." prefix would prevent that, but it is unverifiable, so will make a copy in compat case
return false;
}
return true;
case BoundKind.PointerIndirectionOperator:
case BoundKind.RefValueOperator:
return true;
case BoundKind.ThisReference:
var type = expression.Type;
if (type.IsReferenceType)
{
Debug.Assert(IsAnyReadOnly(addressKind), "`this` is readonly in classes");
return true;
}
if (!IsAnyReadOnly(addressKind) && method.IsEffectivelyReadOnly)
{
return false;
}
return true;
case BoundKind.ThrowExpression:
// vacuously this is true, we can take address of throw without temps
return true;
case BoundKind.Parameter:
return IsAnyReadOnly(addressKind) ||
((BoundParameter)expression).ParameterSymbol.RefKind != RefKind.In;
case BoundKind.Local:
// locals have home unless they are byval stack locals or ref-readonly
// locals in a mutating call
var local = ((BoundLocal)expression).LocalSymbol;
return !((CodeGenerator.IsStackLocal(local, stackLocalsOpt) && local.RefKind == RefKind.None) ||
(!IsAnyReadOnly(addressKind) && local.RefKind == RefKind.RefReadOnly));
case BoundKind.Call:
var methodRefKind = ((BoundCall)expression).Method.RefKind;
return methodRefKind == RefKind.Ref ||
(IsAnyReadOnly(addressKind) && methodRefKind == RefKind.RefReadOnly);
case BoundKind.Dup:
//NB: Dup represents locals that do not need IL slot
var dupRefKind = ((BoundDup)expression).RefKind;
return dupRefKind == RefKind.Ref ||
(IsAnyReadOnly(addressKind) && dupRefKind == RefKind.RefReadOnly);
case BoundKind.FieldAccess:
return HasHome((BoundFieldAccess)expression, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt);
case BoundKind.Sequence:
return HasHome(((BoundSequence)expression).Value, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt);
case BoundKind.AssignmentOperator:
var assignment = (BoundAssignmentOperator)expression;
if (!assignment.IsRef)
{
return false;
}
var lhsRefKind = assignment.Left.GetRefKind();
return lhsRefKind == RefKind.Ref ||
(IsAnyReadOnly(addressKind) && lhsRefKind == RefKind.RefReadOnly);
case BoundKind.ComplexConditionalReceiver:
Debug.Assert(HasHome(
((BoundComplexConditionalReceiver)expression).ValueTypeReceiver,
addressKind,
method,
peVerifyCompatEnabled,
stackLocalsOpt));
Debug.Assert(HasHome(
((BoundComplexConditionalReceiver)expression).ReferenceTypeReceiver,
addressKind,
method,
peVerifyCompatEnabled,
stackLocalsOpt));
goto case BoundKind.ConditionalReceiver;
case BoundKind.ConditionalReceiver:
//ConditionalReceiver is a noop from Emit point of view. - it represents something that has already been pushed.
//We should never need a temp for it.
return true;
case BoundKind.ConditionalOperator:
var conditional = (BoundConditionalOperator)expression;
// only ref conditional may be referenced as a variable
if (!conditional.IsRef)
{
return false;
}
// branch that has no home will need a temporary
// if both have no home, just say whole expression has no home
// so we could just use one temp for the whole thing
return HasHome(conditional.Consequence, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)
&& HasHome(conditional.Alternative, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt);
default:
return false;
}
}
/// <summary>
/// Special HasHome for fields.
/// Fields have readable homes when they are not constants.
/// Fields have writeable homes unless they are readonly and used outside of the constructor.
/// </summary>
private static bool HasHome(
BoundFieldAccess fieldAccess,
AddressKind addressKind,
MethodSymbol method,
bool peVerifyCompatEnabled,
HashSet<LocalSymbol> stackLocalsOpt)
{
Debug.Assert(method is object);
FieldSymbol field = fieldAccess.FieldSymbol;
// const fields are literal values with no homes. (ex: decimal.Zero)
if (field.IsConst)
{
return false;
}
// in readonly situations where ref to a copy is not allowed, consider fields as addressable
if (addressKind == AddressKind.ReadOnlyStrict)
{
return true;
}
// ReadOnly references can always be taken unless we are in peverify compat mode
if (addressKind == AddressKind.ReadOnly && !peVerifyCompatEnabled)
{
return true;
}
// Some field accesses must be values; values do not have homes.
if (fieldAccess.IsByValue)
{
return false;
}
if (!field.IsReadOnly)
{
// in a case if we have a writeable struct field with a receiver that only has a readable home we would need to pass it via a temp.
// it would be advantageous to make a temp for the field, not for the outer struct, since the field is smaller and we can get to is by fetching references.
// NOTE: this would not be profitable if we have to satisfy verifier, since for verifiability
// we would not be able to dig for the inner field using references and the outer struct will have to be copied to a temp anyways.
if (!peVerifyCompatEnabled)
{
Debug.Assert(!IsAnyReadOnly(addressKind));
var receiver = fieldAccess.ReceiverOpt;
if (receiver?.Type.IsValueType == true)
{
// Check receiver:
// has writeable home -> return true - the whole chain has writeable home (also a more common case)
// has readable home -> return false - we need to copy the field
// otherwise -> return true - the copy will be made at higher level so the leaf field can have writeable home
return HasHome(receiver, addressKind, method, peVerifyCompatEnabled, stackLocalsOpt)
|| !HasHome(receiver, AddressKind.ReadOnly, method, peVerifyCompatEnabled, stackLocalsOpt);
}
}
return true;
}
// while readonly fields have home it is not valid to refer to it when not constructing.
if (!TypeSymbol.Equals(field.ContainingType, method.ContainingType, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
if (field.IsStatic)
{
return method.MethodKind == MethodKind.StaticConstructor;
}
else
{
return (method.MethodKind == MethodKind.Constructor || method.IsInitOnly) &&
fieldAccess.ReceiverOpt.Kind == BoundKind.ThisReference;
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Options/SerializableOptionSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Options
{
/// <summary>
/// Serializable implementation of <see cref="OptionSet"/> for <see cref="Solution.Options"/>.
/// It contains prepopulated fetched option values for all serializable options and values, and delegates to <see cref="WorkspaceOptionSet"/> for non-serializable values.
/// It ensures a contract that values are immutable from this instance once observed.
/// </summary>
internal sealed partial class SerializableOptionSet : OptionSet
{
/// <summary>
/// Languages for which all the applicable serializable options have been prefetched and saved in <see cref="_serializableOptionValues"/>.
/// </summary>
private readonly ImmutableHashSet<string> _languages;
/// <summary>
/// Fallback option set for non-serializable options. See comments on <see cref="WorkspaceOptionSet"/> for more details.
/// </summary>
private readonly WorkspaceOptionSet _workspaceOptionSet;
/// <summary>
/// All serializable options for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableHashSet<IOption> _serializableOptions;
/// <summary>
/// Prefetched option values for all <see cref="_serializableOptions"/> applicable for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableDictionary<OptionKey, object?> _serializableOptionValues;
/// <summary>
/// Set of changed options in this option set which are serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysSerializable;
/// <summary>
/// Set of changed options in this option set which are non-serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysNonSerializable;
private SerializableOptionSet(
ImmutableHashSet<string> languages,
WorkspaceOptionSet workspaceOptionSet,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable,
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
_languages = languages;
_workspaceOptionSet = workspaceOptionSet;
_serializableOptions = serializableOptions;
_serializableOptionValues = values;
_changedOptionKeysSerializable = changedOptionKeysSerializable;
_changedOptionKeysNonSerializable = changedOptionKeysNonSerializable;
Debug.Assert(values.Keys.All(ShouldSerialize));
Debug.Assert(changedOptionKeysSerializable.All(optionKey => ShouldSerialize(optionKey)));
Debug.Assert(changedOptionKeysNonSerializable.All(optionKey => !ShouldSerialize(optionKey)));
}
internal SerializableOptionSet(
ImmutableHashSet<string> languages,
IOptionService optionService,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable)
: this(languages, new WorkspaceOptionSet(optionService), serializableOptions, values, changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty)
{
}
/// <summary>
/// Returns an option set with all the serializable option values prefetched for given <paramref name="languages"/>,
/// while also retaining all the explicitly changed option values in this option set for any language.
/// NOTE: All the provided <paramref name="languages"/> must be <see cref="RemoteSupportedLanguages.IsSupported(string)"/>.
/// </summary>
public SerializableOptionSet WithLanguages(ImmutableHashSet<string> languages)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
if (_languages.SetEquals(languages))
{
return this;
}
// First create a base option set for the given languages.
var newOptionSet = _workspaceOptionSet.OptionService.GetSerializableOptionsSnapshot(languages);
// Then apply all the changed options from the current option set to the new option set.
foreach (var changedOption in this.GetChangedOptions())
{
var valueInNewOptionSet = newOptionSet.GetOption(changedOption);
var changedValueInThisOptionSet = this.GetOption(changedOption);
if (!Equals(changedValueInThisOptionSet, valueInNewOptionSet))
{
newOptionSet = (SerializableOptionSet)newOptionSet.WithChangedOption(changedOption, changedValueInThisOptionSet);
}
}
return newOptionSet;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)]
private protected override object? GetOptionCore(OptionKey optionKey)
{
if (_serializableOptionValues.TryGetValue(optionKey, out var value))
{
return value;
}
return _workspaceOptionSet.GetOption(optionKey);
}
private bool ShouldSerialize(OptionKey optionKey)
=> _serializableOptions.Contains(optionKey.Option) &&
(!optionKey.Option.IsPerLanguage || _languages.Contains(optionKey.Language!));
public override OptionSet WithChangedOption(OptionKey optionKey, object? value)
{
// Make sure we first load this in current optionset
var currentValue = this.GetOption(optionKey);
// Check if the new value is the same as the current value.
if (Equals(value, currentValue))
{
// Return a cloned option set as the public API 'WithChangedOption' guarantees a new option set is returned.
return new SerializableOptionSet(_languages, _workspaceOptionSet, _serializableOptions,
_serializableOptionValues, _changedOptionKeysSerializable, _changedOptionKeysNonSerializable);
}
WorkspaceOptionSet workspaceOptionSet;
ImmutableDictionary<OptionKey, object?> serializableOptionValues;
ImmutableHashSet<OptionKey> changedOptionKeysSerializable;
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable;
if (ShouldSerialize(optionKey))
{
workspaceOptionSet = _workspaceOptionSet;
serializableOptionValues = _serializableOptionValues.SetItem(optionKey, value);
changedOptionKeysSerializable = _changedOptionKeysSerializable.Add(optionKey);
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable;
}
else
{
workspaceOptionSet = (WorkspaceOptionSet)_workspaceOptionSet.WithChangedOption(optionKey, value);
serializableOptionValues = _serializableOptionValues;
changedOptionKeysSerializable = _changedOptionKeysSerializable;
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable.Add(optionKey);
}
return new SerializableOptionSet(_languages, workspaceOptionSet, _serializableOptions,
serializableOptionValues, changedOptionKeysSerializable, changedOptionKeysNonSerializable);
}
/// <summary>
/// Gets a list of all the options that were changed.
/// </summary>
internal IEnumerable<OptionKey> GetChangedOptions()
=> _changedOptionKeysSerializable.Concat(_changedOptionKeysNonSerializable);
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet? optionSet)
{
if (optionSet == this)
{
yield break;
}
foreach (var key in GetChangedOptions())
{
var currentValue = optionSet?.GetOption(key);
var changedValue = this.GetOption(key);
if (!object.Equals(currentValue, changedValue))
{
yield return key;
}
}
}
public void Serialize(ObjectWriter writer, CancellationToken cancellationToken)
{
// We serialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the serialization in sync with Deserialize method below.
cancellationToken.ThrowIfCancellationRequested();
writer.WriteInt32(_languages.Count);
foreach (var language in _languages.Order())
{
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
writer.WriteString(language);
}
var valuesBuilder = new SortedDictionary<OptionKey, (OptionValueKind, object?)>(OptionKeyComparer.Instance);
foreach (var (optionKey, value) in _serializableOptionValues)
{
Debug.Assert(ShouldSerialize(optionKey));
if (!_serializableOptions.Contains(optionKey.Option))
{
continue;
}
var kind = OptionValueKind.Null;
object? valueToWrite = null;
if (value != null)
{
switch (value)
{
case ICodeStyleOption codeStyleOption:
if (optionKey.Option.Type.GenericTypeArguments.Length != 1)
{
continue;
}
kind = OptionValueKind.CodeStyleOption;
valueToWrite = codeStyleOption;
break;
case NamingStylePreferences stylePreferences:
kind = OptionValueKind.NamingStylePreferences;
valueToWrite = stylePreferences;
break;
case string str:
kind = OptionValueKind.String;
valueToWrite = str;
break;
default:
var type = value.GetType();
if (type.IsEnum)
{
kind = OptionValueKind.Enum;
valueToWrite = (int)value;
break;
}
if (optionKey.Option.Type.IsSerializable)
{
kind = OptionValueKind.Serializable;
valueToWrite = value;
break;
}
continue;
}
}
valuesBuilder.Add(optionKey, (kind, valueToWrite));
}
writer.WriteInt32(valuesBuilder.Count);
foreach (var (optionKey, (kind, value)) in valuesBuilder)
{
SerializeOptionKey(optionKey);
writer.WriteInt32((int)kind);
if (kind == OptionValueKind.Enum)
{
RoslynDebug.Assert(value != null);
writer.WriteInt32((int)value);
}
else if (kind == OptionValueKind.CodeStyleOption || kind == OptionValueKind.NamingStylePreferences)
{
RoslynDebug.Assert(value != null);
((IObjectWritable)value).WriteTo(writer);
}
else
{
writer.WriteValue(value);
}
}
writer.WriteInt32(_changedOptionKeysSerializable.Count);
foreach (var changedKey in _changedOptionKeysSerializable.OrderBy(OptionKeyComparer.Instance))
{
SerializeOptionKey(changedKey);
}
return;
void SerializeOptionKey(OptionKey optionKey)
{
Debug.Assert(ShouldSerialize(optionKey));
writer.WriteString(optionKey.Option.Name);
writer.WriteString(optionKey.Option.Feature);
writer.WriteBoolean(optionKey.Option.IsPerLanguage);
if (optionKey.Option.IsPerLanguage)
{
writer.WriteString(optionKey.Language);
}
}
}
public static SerializableOptionSet Deserialize(ObjectReader reader, IOptionService optionService, CancellationToken cancellationToken)
{
// We deserialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the deserialization in sync with Serialize method above.
cancellationToken.ThrowIfCancellationRequested();
var count = reader.ReadInt32();
var languagesBuilder = ImmutableHashSet.CreateBuilder<string>();
for (var i = 0; i < count; i++)
{
var language = reader.ReadString();
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
languagesBuilder.Add(language);
}
var languages = languagesBuilder.ToImmutable();
var serializableOptions = optionService.GetRegisteredSerializableOptions(languages);
var lookup = serializableOptions.ToLookup(o => o.Name);
count = reader.ReadInt32();
var builder = ImmutableDictionary.CreateBuilder<OptionKey, object?>();
for (var i = 0; i < count; i++)
{
if (!TryDeserializeOptionKey(reader, lookup, out var optionKey))
{
continue;
}
var kind = (OptionValueKind)reader.ReadInt32();
var readValue = kind switch
{
OptionValueKind.Enum => reader.ReadInt32(),
OptionValueKind.CodeStyleOption => CodeStyleOption2<object>.ReadFrom(reader),
OptionValueKind.NamingStylePreferences => NamingStylePreferences.ReadFrom(reader),
_ => reader.ReadValue(),
};
if (!serializableOptions.Contains(optionKey.Option))
{
continue;
}
object? optionValue;
switch (kind)
{
case OptionValueKind.CodeStyleOption:
var defaultValue = optionKey.Option.DefaultValue as ICodeStyleOption;
if (defaultValue == null ||
optionKey.Option.Type.GenericTypeArguments.Length != 1)
{
continue;
}
var parsedCodeStyleOption = (CodeStyleOption2<object>)readValue;
var value = parsedCodeStyleOption.Value;
var type = optionKey.Option.Type.GenericTypeArguments[0];
var convertedValue = type.IsEnum ? Enum.ToObject(type, value) : Convert.ChangeType(value, type);
optionValue = defaultValue.WithValue(convertedValue).WithNotification(parsedCodeStyleOption.Notification);
break;
case OptionValueKind.NamingStylePreferences:
optionValue = (NamingStylePreferences)readValue;
break;
case OptionValueKind.Enum:
optionValue = Enum.ToObject(optionKey.Option.Type, readValue);
break;
case OptionValueKind.Null:
optionValue = null;
break;
default:
optionValue = readValue;
break;
}
builder[optionKey] = optionValue;
}
count = reader.ReadInt32();
var changedKeysBuilder = ImmutableHashSet.CreateBuilder<OptionKey>();
for (var i = 0; i < count; i++)
{
if (TryDeserializeOptionKey(reader, lookup, out var optionKey))
{
changedKeysBuilder.Add(optionKey);
}
}
var serializableOptionValues = builder.ToImmutable();
var changedOptionKeysSerializable = changedKeysBuilder.ToImmutable();
var workspaceOptionSet = new WorkspaceOptionSet(optionService);
return new SerializableOptionSet(languages, workspaceOptionSet, serializableOptions, serializableOptionValues,
changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty);
static bool TryDeserializeOptionKey(ObjectReader reader, ILookup<string, IOption> lookup, out OptionKey deserializedOptionKey)
{
var name = reader.ReadString();
var feature = reader.ReadString();
var isPerLanguage = reader.ReadBoolean();
var language = isPerLanguage ? reader.ReadString() : null;
foreach (var option in lookup[name])
{
if (option.Feature == feature &&
option.IsPerLanguage == isPerLanguage)
{
deserializedOptionKey = new OptionKey(option, language);
return true;
}
}
deserializedOptionKey = default;
return false;
}
}
private enum OptionValueKind
{
Null,
CodeStyleOption,
NamingStylePreferences,
Serializable,
String,
Enum
}
private sealed class OptionKeyComparer : IComparer<OptionKey>
{
public static readonly OptionKeyComparer Instance = new();
private OptionKeyComparer() { }
public int Compare(OptionKey x, OptionKey y)
{
if (x.Option.Name != y.Option.Name)
{
return StringComparer.Ordinal.Compare(x.Option.Name, y.Option.Name);
}
if (x.Option.Feature != y.Option.Feature)
{
return StringComparer.Ordinal.Compare(x.Option.Feature, y.Option.Feature);
}
if (x.Language != y.Language)
{
return StringComparer.Ordinal.Compare(x.Language, y.Language);
}
return Comparer.Default.Compare(x.GetHashCode(), y.GetHashCode());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Remote;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Options
{
/// <summary>
/// Serializable implementation of <see cref="OptionSet"/> for <see cref="Solution.Options"/>.
/// It contains prepopulated fetched option values for all serializable options and values, and delegates to <see cref="WorkspaceOptionSet"/> for non-serializable values.
/// It ensures a contract that values are immutable from this instance once observed.
/// </summary>
internal sealed partial class SerializableOptionSet : OptionSet
{
/// <summary>
/// Languages for which all the applicable serializable options have been prefetched and saved in <see cref="_serializableOptionValues"/>.
/// </summary>
private readonly ImmutableHashSet<string> _languages;
/// <summary>
/// Fallback option set for non-serializable options. See comments on <see cref="WorkspaceOptionSet"/> for more details.
/// </summary>
private readonly WorkspaceOptionSet _workspaceOptionSet;
/// <summary>
/// All serializable options for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableHashSet<IOption> _serializableOptions;
/// <summary>
/// Prefetched option values for all <see cref="_serializableOptions"/> applicable for <see cref="_languages"/>.
/// </summary>
private readonly ImmutableDictionary<OptionKey, object?> _serializableOptionValues;
/// <summary>
/// Set of changed options in this option set which are serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysSerializable;
/// <summary>
/// Set of changed options in this option set which are non-serializable.
/// </summary>
private readonly ImmutableHashSet<OptionKey> _changedOptionKeysNonSerializable;
private SerializableOptionSet(
ImmutableHashSet<string> languages,
WorkspaceOptionSet workspaceOptionSet,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable,
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
_languages = languages;
_workspaceOptionSet = workspaceOptionSet;
_serializableOptions = serializableOptions;
_serializableOptionValues = values;
_changedOptionKeysSerializable = changedOptionKeysSerializable;
_changedOptionKeysNonSerializable = changedOptionKeysNonSerializable;
Debug.Assert(values.Keys.All(ShouldSerialize));
Debug.Assert(changedOptionKeysSerializable.All(optionKey => ShouldSerialize(optionKey)));
Debug.Assert(changedOptionKeysNonSerializable.All(optionKey => !ShouldSerialize(optionKey)));
}
internal SerializableOptionSet(
ImmutableHashSet<string> languages,
IOptionService optionService,
ImmutableHashSet<IOption> serializableOptions,
ImmutableDictionary<OptionKey, object?> values,
ImmutableHashSet<OptionKey> changedOptionKeysSerializable)
: this(languages, new WorkspaceOptionSet(optionService), serializableOptions, values, changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty)
{
}
/// <summary>
/// Returns an option set with all the serializable option values prefetched for given <paramref name="languages"/>,
/// while also retaining all the explicitly changed option values in this option set for any language.
/// NOTE: All the provided <paramref name="languages"/> must be <see cref="RemoteSupportedLanguages.IsSupported(string)"/>.
/// </summary>
public SerializableOptionSet WithLanguages(ImmutableHashSet<string> languages)
{
Debug.Assert(languages.All(RemoteSupportedLanguages.IsSupported));
if (_languages.SetEquals(languages))
{
return this;
}
// First create a base option set for the given languages.
var newOptionSet = _workspaceOptionSet.OptionService.GetSerializableOptionsSnapshot(languages);
// Then apply all the changed options from the current option set to the new option set.
foreach (var changedOption in this.GetChangedOptions())
{
var valueInNewOptionSet = newOptionSet.GetOption(changedOption);
var changedValueInThisOptionSet = this.GetOption(changedOption);
if (!Equals(changedValueInThisOptionSet, valueInNewOptionSet))
{
newOptionSet = (SerializableOptionSet)newOptionSet.WithChangedOption(changedOption, changedValueInThisOptionSet);
}
}
return newOptionSet;
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)]
private protected override object? GetOptionCore(OptionKey optionKey)
{
if (_serializableOptionValues.TryGetValue(optionKey, out var value))
{
return value;
}
return _workspaceOptionSet.GetOption(optionKey);
}
private bool ShouldSerialize(OptionKey optionKey)
=> _serializableOptions.Contains(optionKey.Option) &&
(!optionKey.Option.IsPerLanguage || _languages.Contains(optionKey.Language!));
public override OptionSet WithChangedOption(OptionKey optionKey, object? value)
{
// Make sure we first load this in current optionset
var currentValue = this.GetOption(optionKey);
// Check if the new value is the same as the current value.
if (Equals(value, currentValue))
{
// Return a cloned option set as the public API 'WithChangedOption' guarantees a new option set is returned.
return new SerializableOptionSet(_languages, _workspaceOptionSet, _serializableOptions,
_serializableOptionValues, _changedOptionKeysSerializable, _changedOptionKeysNonSerializable);
}
WorkspaceOptionSet workspaceOptionSet;
ImmutableDictionary<OptionKey, object?> serializableOptionValues;
ImmutableHashSet<OptionKey> changedOptionKeysSerializable;
ImmutableHashSet<OptionKey> changedOptionKeysNonSerializable;
if (ShouldSerialize(optionKey))
{
workspaceOptionSet = _workspaceOptionSet;
serializableOptionValues = _serializableOptionValues.SetItem(optionKey, value);
changedOptionKeysSerializable = _changedOptionKeysSerializable.Add(optionKey);
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable;
}
else
{
workspaceOptionSet = (WorkspaceOptionSet)_workspaceOptionSet.WithChangedOption(optionKey, value);
serializableOptionValues = _serializableOptionValues;
changedOptionKeysSerializable = _changedOptionKeysSerializable;
changedOptionKeysNonSerializable = _changedOptionKeysNonSerializable.Add(optionKey);
}
return new SerializableOptionSet(_languages, workspaceOptionSet, _serializableOptions,
serializableOptionValues, changedOptionKeysSerializable, changedOptionKeysNonSerializable);
}
/// <summary>
/// Gets a list of all the options that were changed.
/// </summary>
internal IEnumerable<OptionKey> GetChangedOptions()
=> _changedOptionKeysSerializable.Concat(_changedOptionKeysNonSerializable);
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet? optionSet)
{
if (optionSet == this)
{
yield break;
}
foreach (var key in GetChangedOptions())
{
var currentValue = optionSet?.GetOption(key);
var changedValue = this.GetOption(key);
if (!object.Equals(currentValue, changedValue))
{
yield return key;
}
}
}
public void Serialize(ObjectWriter writer, CancellationToken cancellationToken)
{
// We serialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the serialization in sync with Deserialize method below.
cancellationToken.ThrowIfCancellationRequested();
writer.WriteInt32(_languages.Count);
foreach (var language in _languages.Order())
{
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
writer.WriteString(language);
}
var valuesBuilder = new SortedDictionary<OptionKey, (OptionValueKind, object?)>(OptionKeyComparer.Instance);
foreach (var (optionKey, value) in _serializableOptionValues)
{
Debug.Assert(ShouldSerialize(optionKey));
if (!_serializableOptions.Contains(optionKey.Option))
{
continue;
}
var kind = OptionValueKind.Null;
object? valueToWrite = null;
if (value != null)
{
switch (value)
{
case ICodeStyleOption codeStyleOption:
if (optionKey.Option.Type.GenericTypeArguments.Length != 1)
{
continue;
}
kind = OptionValueKind.CodeStyleOption;
valueToWrite = codeStyleOption;
break;
case NamingStylePreferences stylePreferences:
kind = OptionValueKind.NamingStylePreferences;
valueToWrite = stylePreferences;
break;
case string str:
kind = OptionValueKind.String;
valueToWrite = str;
break;
default:
var type = value.GetType();
if (type.IsEnum)
{
kind = OptionValueKind.Enum;
valueToWrite = (int)value;
break;
}
if (optionKey.Option.Type.IsSerializable)
{
kind = OptionValueKind.Serializable;
valueToWrite = value;
break;
}
continue;
}
}
valuesBuilder.Add(optionKey, (kind, valueToWrite));
}
writer.WriteInt32(valuesBuilder.Count);
foreach (var (optionKey, (kind, value)) in valuesBuilder)
{
SerializeOptionKey(optionKey);
writer.WriteInt32((int)kind);
if (kind == OptionValueKind.Enum)
{
RoslynDebug.Assert(value != null);
writer.WriteInt32((int)value);
}
else if (kind == OptionValueKind.CodeStyleOption || kind == OptionValueKind.NamingStylePreferences)
{
RoslynDebug.Assert(value != null);
((IObjectWritable)value).WriteTo(writer);
}
else
{
writer.WriteValue(value);
}
}
writer.WriteInt32(_changedOptionKeysSerializable.Count);
foreach (var changedKey in _changedOptionKeysSerializable.OrderBy(OptionKeyComparer.Instance))
{
SerializeOptionKey(changedKey);
}
return;
void SerializeOptionKey(OptionKey optionKey)
{
Debug.Assert(ShouldSerialize(optionKey));
writer.WriteString(optionKey.Option.Name);
writer.WriteString(optionKey.Option.Feature);
writer.WriteBoolean(optionKey.Option.IsPerLanguage);
if (optionKey.Option.IsPerLanguage)
{
writer.WriteString(optionKey.Language);
}
}
}
public static SerializableOptionSet Deserialize(ObjectReader reader, IOptionService optionService, CancellationToken cancellationToken)
{
// We deserialize the following contents from this option set:
// 1. Languages
// 2. Prefetched serializable option key-value pairs
// 3. Changed option keys.
// NOTE: keep the deserialization in sync with Serialize method above.
cancellationToken.ThrowIfCancellationRequested();
var count = reader.ReadInt32();
var languagesBuilder = ImmutableHashSet.CreateBuilder<string>();
for (var i = 0; i < count; i++)
{
var language = reader.ReadString();
Debug.Assert(RemoteSupportedLanguages.IsSupported(language));
languagesBuilder.Add(language);
}
var languages = languagesBuilder.ToImmutable();
var serializableOptions = optionService.GetRegisteredSerializableOptions(languages);
var lookup = serializableOptions.ToLookup(o => o.Name);
count = reader.ReadInt32();
var builder = ImmutableDictionary.CreateBuilder<OptionKey, object?>();
for (var i = 0; i < count; i++)
{
if (!TryDeserializeOptionKey(reader, lookup, out var optionKey))
{
continue;
}
var kind = (OptionValueKind)reader.ReadInt32();
var readValue = kind switch
{
OptionValueKind.Enum => reader.ReadInt32(),
OptionValueKind.CodeStyleOption => CodeStyleOption2<object>.ReadFrom(reader),
OptionValueKind.NamingStylePreferences => NamingStylePreferences.ReadFrom(reader),
_ => reader.ReadValue(),
};
if (!serializableOptions.Contains(optionKey.Option))
{
continue;
}
object? optionValue;
switch (kind)
{
case OptionValueKind.CodeStyleOption:
var defaultValue = optionKey.Option.DefaultValue as ICodeStyleOption;
if (defaultValue == null ||
optionKey.Option.Type.GenericTypeArguments.Length != 1)
{
continue;
}
var parsedCodeStyleOption = (CodeStyleOption2<object>)readValue;
var value = parsedCodeStyleOption.Value;
var type = optionKey.Option.Type.GenericTypeArguments[0];
var convertedValue = type.IsEnum ? Enum.ToObject(type, value) : Convert.ChangeType(value, type);
optionValue = defaultValue.WithValue(convertedValue).WithNotification(parsedCodeStyleOption.Notification);
break;
case OptionValueKind.NamingStylePreferences:
optionValue = (NamingStylePreferences)readValue;
break;
case OptionValueKind.Enum:
optionValue = Enum.ToObject(optionKey.Option.Type, readValue);
break;
case OptionValueKind.Null:
optionValue = null;
break;
default:
optionValue = readValue;
break;
}
builder[optionKey] = optionValue;
}
count = reader.ReadInt32();
var changedKeysBuilder = ImmutableHashSet.CreateBuilder<OptionKey>();
for (var i = 0; i < count; i++)
{
if (TryDeserializeOptionKey(reader, lookup, out var optionKey))
{
changedKeysBuilder.Add(optionKey);
}
}
var serializableOptionValues = builder.ToImmutable();
var changedOptionKeysSerializable = changedKeysBuilder.ToImmutable();
var workspaceOptionSet = new WorkspaceOptionSet(optionService);
return new SerializableOptionSet(languages, workspaceOptionSet, serializableOptions, serializableOptionValues,
changedOptionKeysSerializable, changedOptionKeysNonSerializable: ImmutableHashSet<OptionKey>.Empty);
static bool TryDeserializeOptionKey(ObjectReader reader, ILookup<string, IOption> lookup, out OptionKey deserializedOptionKey)
{
var name = reader.ReadString();
var feature = reader.ReadString();
var isPerLanguage = reader.ReadBoolean();
var language = isPerLanguage ? reader.ReadString() : null;
foreach (var option in lookup[name])
{
if (option.Feature == feature &&
option.IsPerLanguage == isPerLanguage)
{
deserializedOptionKey = new OptionKey(option, language);
return true;
}
}
deserializedOptionKey = default;
return false;
}
}
private enum OptionValueKind
{
Null,
CodeStyleOption,
NamingStylePreferences,
Serializable,
String,
Enum
}
private sealed class OptionKeyComparer : IComparer<OptionKey>
{
public static readonly OptionKeyComparer Instance = new();
private OptionKeyComparer() { }
public int Compare(OptionKey x, OptionKey y)
{
if (x.Option.Name != y.Option.Name)
{
return StringComparer.Ordinal.Compare(x.Option.Name, y.Option.Name);
}
if (x.Option.Feature != y.Option.Feature)
{
return StringComparer.Ordinal.Compare(x.Option.Feature, y.Option.Feature);
}
if (x.Language != y.Language)
{
return StringComparer.Ordinal.Compare(x.Language, y.Language);
}
return Comparer.Default.Compare(x.GetHashCode(), y.GetHashCode());
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Classification/Classifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
public static class Classifier
{
public static async Task<IEnumerable<ClassifiedSpan>> GetClassifiedSpansAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken = default)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return GetClassifiedSpans(semanticModel, textSpan, document.Project.Solution.Workspace, cancellationToken);
}
/// <summary>
/// Returns classified spans in ascending <see cref="ClassifiedSpan"/> order.
/// <see cref="ClassifiedSpan"/>s may have the same <see cref="ClassifiedSpan.TextSpan"/>. This occurs when there are multiple
/// <see cref="ClassifiedSpan.ClassificationType"/>s for the same region of code. For example, a reference to a static method
/// will have two spans, one that designates it as a method, and one that designates it as static.
/// <see cref="ClassifiedSpan"/>s may also have overlapping <see cref="ClassifiedSpan.TextSpan"/>s. This occurs when there are
/// strings containing regex and/or escape characters.
/// </summary>
public static IEnumerable<ClassifiedSpan> GetClassifiedSpans(
SemanticModel semanticModel,
TextSpan textSpan,
Workspace workspace,
CancellationToken cancellationToken = default)
{
var service = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxClassificationService>();
var syntaxClassifiers = service.GetDefaultSyntaxClassifiers();
var extensionManager = workspace.Services.GetRequiredService<IExtensionManager>();
var getNodeClassifiers = extensionManager.CreateNodeExtensionGetter(syntaxClassifiers, c => c.SyntaxNodeTypes);
var getTokenClassifiers = extensionManager.CreateTokenExtensionGetter(syntaxClassifiers, c => c.SyntaxTokenKinds);
using var _1 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var syntacticClassifications);
using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var semanticClassifications);
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
service.AddSyntacticClassifications(root, textSpan, syntacticClassifications, cancellationToken);
service.AddSemanticClassifications(semanticModel, textSpan, workspace, getNodeClassifiers, getTokenClassifiers, semanticClassifications, cancellationToken);
var allClassifications = new List<ClassifiedSpan>(semanticClassifications.Where(s => s.TextSpan.OverlapsWith(textSpan)));
var semanticSet = semanticClassifications.Select(s => s.TextSpan).ToSet();
allClassifications.AddRange(syntacticClassifications.Where(
s => s.TextSpan.OverlapsWith(textSpan) && !semanticSet.Contains(s.TextSpan)));
allClassifications.Sort((s1, s2) => s1.TextSpan.Start - s2.TextSpan.Start);
return allClassifications;
}
internal static async Task<ImmutableArray<SymbolDisplayPart>> GetClassifiedSymbolDisplayPartsAsync(
SemanticModel semanticModel, TextSpan textSpan, Workspace workspace,
CancellationToken cancellationToken = default)
{
var classifiedSpans = GetClassifiedSpans(semanticModel, textSpan, workspace, cancellationToken);
var sourceText = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return ConvertClassificationsToParts(sourceText, textSpan.Start, classifiedSpans);
}
internal static ImmutableArray<SymbolDisplayPart> ConvertClassificationsToParts(
SourceText sourceText, int startPosition, IEnumerable<ClassifiedSpan> classifiedSpans)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
foreach (var span in classifiedSpans)
{
// If there is space between this span and the last one, then add a space.
if (startPosition < span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, sourceText.ToString(span.TextSpan)));
startPosition = span.TextSpan.End;
}
}
return parts.ToImmutableAndFree();
}
private static IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
private static SymbolDisplayPartKind? GetClassificationKind(string type)
=> type switch
{
ClassificationTypeNames.Identifier => SymbolDisplayPartKind.Text,
ClassificationTypeNames.Keyword => SymbolDisplayPartKind.Keyword,
ClassificationTypeNames.NumericLiteral => SymbolDisplayPartKind.NumericLiteral,
ClassificationTypeNames.StringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.WhiteSpace => SymbolDisplayPartKind.Space,
ClassificationTypeNames.Operator => SymbolDisplayPartKind.Operator,
ClassificationTypeNames.Punctuation => SymbolDisplayPartKind.Punctuation,
ClassificationTypeNames.ClassName => SymbolDisplayPartKind.ClassName,
ClassificationTypeNames.RecordClassName => SymbolDisplayPartKind.RecordClassName,
ClassificationTypeNames.StructName => SymbolDisplayPartKind.StructName,
ClassificationTypeNames.InterfaceName => SymbolDisplayPartKind.InterfaceName,
ClassificationTypeNames.DelegateName => SymbolDisplayPartKind.DelegateName,
ClassificationTypeNames.EnumName => SymbolDisplayPartKind.EnumName,
ClassificationTypeNames.TypeParameterName => SymbolDisplayPartKind.TypeParameterName,
ClassificationTypeNames.ModuleName => SymbolDisplayPartKind.ModuleName,
ClassificationTypeNames.VerbatimStringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.FieldName => SymbolDisplayPartKind.FieldName,
ClassificationTypeNames.EnumMemberName => SymbolDisplayPartKind.EnumMemberName,
ClassificationTypeNames.ConstantName => SymbolDisplayPartKind.ConstantName,
ClassificationTypeNames.LocalName => SymbolDisplayPartKind.LocalName,
ClassificationTypeNames.ParameterName => SymbolDisplayPartKind.ParameterName,
ClassificationTypeNames.ExtensionMethodName => SymbolDisplayPartKind.ExtensionMethodName,
ClassificationTypeNames.MethodName => SymbolDisplayPartKind.MethodName,
ClassificationTypeNames.PropertyName => SymbolDisplayPartKind.PropertyName,
ClassificationTypeNames.LabelName => SymbolDisplayPartKind.LabelName,
ClassificationTypeNames.NamespaceName => SymbolDisplayPartKind.NamespaceName,
ClassificationTypeNames.EventName => SymbolDisplayPartKind.EventName,
_ => null,
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
public static class Classifier
{
public static async Task<IEnumerable<ClassifiedSpan>> GetClassifiedSpansAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken = default)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return GetClassifiedSpans(semanticModel, textSpan, document.Project.Solution.Workspace, cancellationToken);
}
/// <summary>
/// Returns classified spans in ascending <see cref="ClassifiedSpan"/> order.
/// <see cref="ClassifiedSpan"/>s may have the same <see cref="ClassifiedSpan.TextSpan"/>. This occurs when there are multiple
/// <see cref="ClassifiedSpan.ClassificationType"/>s for the same region of code. For example, a reference to a static method
/// will have two spans, one that designates it as a method, and one that designates it as static.
/// <see cref="ClassifiedSpan"/>s may also have overlapping <see cref="ClassifiedSpan.TextSpan"/>s. This occurs when there are
/// strings containing regex and/or escape characters.
/// </summary>
public static IEnumerable<ClassifiedSpan> GetClassifiedSpans(
SemanticModel semanticModel,
TextSpan textSpan,
Workspace workspace,
CancellationToken cancellationToken = default)
{
var service = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxClassificationService>();
var syntaxClassifiers = service.GetDefaultSyntaxClassifiers();
var extensionManager = workspace.Services.GetRequiredService<IExtensionManager>();
var getNodeClassifiers = extensionManager.CreateNodeExtensionGetter(syntaxClassifiers, c => c.SyntaxNodeTypes);
var getTokenClassifiers = extensionManager.CreateTokenExtensionGetter(syntaxClassifiers, c => c.SyntaxTokenKinds);
using var _1 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var syntacticClassifications);
using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var semanticClassifications);
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
service.AddSyntacticClassifications(root, textSpan, syntacticClassifications, cancellationToken);
service.AddSemanticClassifications(semanticModel, textSpan, workspace, getNodeClassifiers, getTokenClassifiers, semanticClassifications, cancellationToken);
var allClassifications = new List<ClassifiedSpan>(semanticClassifications.Where(s => s.TextSpan.OverlapsWith(textSpan)));
var semanticSet = semanticClassifications.Select(s => s.TextSpan).ToSet();
allClassifications.AddRange(syntacticClassifications.Where(
s => s.TextSpan.OverlapsWith(textSpan) && !semanticSet.Contains(s.TextSpan)));
allClassifications.Sort((s1, s2) => s1.TextSpan.Start - s2.TextSpan.Start);
return allClassifications;
}
internal static async Task<ImmutableArray<SymbolDisplayPart>> GetClassifiedSymbolDisplayPartsAsync(
SemanticModel semanticModel, TextSpan textSpan, Workspace workspace,
CancellationToken cancellationToken = default)
{
var classifiedSpans = GetClassifiedSpans(semanticModel, textSpan, workspace, cancellationToken);
var sourceText = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return ConvertClassificationsToParts(sourceText, textSpan.Start, classifiedSpans);
}
internal static ImmutableArray<SymbolDisplayPart> ConvertClassificationsToParts(
SourceText sourceText, int startPosition, IEnumerable<ClassifiedSpan> classifiedSpans)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
foreach (var span in classifiedSpans)
{
// If there is space between this span and the last one, then add a space.
if (startPosition < span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, sourceText.ToString(span.TextSpan)));
startPosition = span.TextSpan.End;
}
}
return parts.ToImmutableAndFree();
}
private static IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
private static SymbolDisplayPartKind? GetClassificationKind(string type)
=> type switch
{
ClassificationTypeNames.Identifier => SymbolDisplayPartKind.Text,
ClassificationTypeNames.Keyword => SymbolDisplayPartKind.Keyword,
ClassificationTypeNames.NumericLiteral => SymbolDisplayPartKind.NumericLiteral,
ClassificationTypeNames.StringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.WhiteSpace => SymbolDisplayPartKind.Space,
ClassificationTypeNames.Operator => SymbolDisplayPartKind.Operator,
ClassificationTypeNames.Punctuation => SymbolDisplayPartKind.Punctuation,
ClassificationTypeNames.ClassName => SymbolDisplayPartKind.ClassName,
ClassificationTypeNames.RecordClassName => SymbolDisplayPartKind.RecordClassName,
ClassificationTypeNames.StructName => SymbolDisplayPartKind.StructName,
ClassificationTypeNames.InterfaceName => SymbolDisplayPartKind.InterfaceName,
ClassificationTypeNames.DelegateName => SymbolDisplayPartKind.DelegateName,
ClassificationTypeNames.EnumName => SymbolDisplayPartKind.EnumName,
ClassificationTypeNames.TypeParameterName => SymbolDisplayPartKind.TypeParameterName,
ClassificationTypeNames.ModuleName => SymbolDisplayPartKind.ModuleName,
ClassificationTypeNames.VerbatimStringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.FieldName => SymbolDisplayPartKind.FieldName,
ClassificationTypeNames.EnumMemberName => SymbolDisplayPartKind.EnumMemberName,
ClassificationTypeNames.ConstantName => SymbolDisplayPartKind.ConstantName,
ClassificationTypeNames.LocalName => SymbolDisplayPartKind.LocalName,
ClassificationTypeNames.ParameterName => SymbolDisplayPartKind.ParameterName,
ClassificationTypeNames.ExtensionMethodName => SymbolDisplayPartKind.ExtensionMethodName,
ClassificationTypeNames.MethodName => SymbolDisplayPartKind.MethodName,
ClassificationTypeNames.PropertyName => SymbolDisplayPartKind.PropertyName,
ClassificationTypeNames.LabelName => SymbolDisplayPartKind.LabelName,
ClassificationTypeNames.NamespaceName => SymbolDisplayPartKind.NamespaceName,
ClassificationTypeNames.EventName => SymbolDisplayPartKind.EventName,
_ => null,
};
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Diagnostics/ISupportLiveUpdate.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Marker interface to indicate whether given diagnostic args are from live analysis.
/// </summary>
internal interface ISupportLiveUpdate
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Marker interface to indicate whether given diagnostic args are from live analysis.
/// </summary>
internal interface ISupportLiveUpdate
{
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/CodeFixes/RemoveUnnecessaryDiscardDesignation/CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryDiscardDesignation
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryDiscardDesignation), Shared]
internal partial class CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryDiscardDesignationDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)),
diagnostic);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var generator = editor.Generator;
foreach (var diagnostic in diagnostics)
{
var discard = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken);
switch (discard.Parent)
{
case DeclarationPatternSyntax declarationPattern:
if (declarationPattern.Parent is IsPatternExpressionSyntax isPattern)
{
editor.ReplaceNode(
isPattern,
(current, _) =>
{
var currentIsPattern = (IsPatternExpressionSyntax)current;
return SyntaxFactory.BinaryExpression(
SyntaxKind.IsExpression,
currentIsPattern.Expression,
currentIsPattern.IsKeyword,
((DeclarationPatternSyntax)isPattern.Pattern).Type)
.WithAdditionalAnnotations(Formatter.Annotation);
});
}
else
{
editor.ReplaceNode(
declarationPattern,
(current, _) =>
SyntaxFactory.TypePattern(((DeclarationPatternSyntax)current).Type)
.WithAdditionalAnnotations(Formatter.Annotation));
}
break;
case RecursivePatternSyntax recursivePattern:
editor.ReplaceNode(
recursivePattern,
(current, _) =>
((RecursivePatternSyntax)current).WithDesignation(null)
.WithAdditionalAnnotations(Formatter.Annotation));
break;
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(
Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Remove_unnessary_discard, createChangedDocument, CSharpAnalyzersResources.Remove_unnessary_discard)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryDiscardDesignation
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryDiscardDesignation), Shared]
internal partial class CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRemoveUnnecessaryDiscardDesignationCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
=> ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryDiscardDesignationDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
context.RegisterCodeFix(
new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)),
diagnostic);
return Task.CompletedTask;
}
protected override Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var generator = editor.Generator;
foreach (var diagnostic in diagnostics)
{
var discard = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken);
switch (discard.Parent)
{
case DeclarationPatternSyntax declarationPattern:
if (declarationPattern.Parent is IsPatternExpressionSyntax isPattern)
{
editor.ReplaceNode(
isPattern,
(current, _) =>
{
var currentIsPattern = (IsPatternExpressionSyntax)current;
return SyntaxFactory.BinaryExpression(
SyntaxKind.IsExpression,
currentIsPattern.Expression,
currentIsPattern.IsKeyword,
((DeclarationPatternSyntax)isPattern.Pattern).Type)
.WithAdditionalAnnotations(Formatter.Annotation);
});
}
else
{
editor.ReplaceNode(
declarationPattern,
(current, _) =>
SyntaxFactory.TypePattern(((DeclarationPatternSyntax)current).Type)
.WithAdditionalAnnotations(Formatter.Annotation));
}
break;
case RecursivePatternSyntax recursivePattern:
editor.ReplaceNode(
recursivePattern,
(current, _) =>
((RecursivePatternSyntax)current).WithDesignation(null)
.WithAdditionalAnnotations(Formatter.Annotation));
break;
}
}
return Task.CompletedTask;
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(
Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Remove_unnessary_discard, createChangedDocument, CSharpAnalyzersResources.Remove_unnessary_discard)
{
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/MSBuildTask/Csc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines the "Csc" XMake task, which enables building assemblies from C#
/// source files by invoking the C# compiler. This is the new Roslyn XMake task,
/// meaning that the code is compiled by using the Roslyn compiler server, rather
/// than csc.exe. The two should be functionally identical, but the compiler server
/// should be significantly faster with larger projects and have a smaller memory
/// footprint.
/// </summary>
public class Csc : ManagedCompiler
{
#region Properties
// Please keep these alphabetized. These are the parameters specific to Csc. The
// ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
// the base class.
public bool AllowUnsafeBlocks
{
set { _store[nameof(AllowUnsafeBlocks)] = value; }
get { return _store.GetOrDefault(nameof(AllowUnsafeBlocks), false); }
}
public string? ApplicationConfiguration
{
set { _store[nameof(ApplicationConfiguration)] = value; }
get { return (string?)_store[nameof(ApplicationConfiguration)]; }
}
public string? BaseAddress
{
set { _store[nameof(BaseAddress)] = value; }
get { return (string?)_store[nameof(BaseAddress)]; }
}
public bool CheckForOverflowUnderflow
{
set { _store[nameof(CheckForOverflowUnderflow)] = value; }
get { return _store.GetOrDefault(nameof(CheckForOverflowUnderflow), false); }
}
public string? DocumentationFile
{
set { _store[nameof(DocumentationFile)] = value; }
get { return (string?)_store[nameof(DocumentationFile)]; }
}
public string? DisabledWarnings
{
set { _store[nameof(DisabledWarnings)] = value; }
get { return (string?)_store[nameof(DisabledWarnings)]; }
}
public bool DisableSdkPath
{
set { _store[nameof(DisableSdkPath)] = value; }
get { return _store.GetOrDefault(nameof(DisableSdkPath), false); }
}
public bool ErrorEndLocation
{
set { _store[nameof(ErrorEndLocation)] = value; }
get { return _store.GetOrDefault(nameof(ErrorEndLocation), false); }
}
public string? ErrorReport
{
set { _store[nameof(ErrorReport)] = value; }
get { return (string?)_store[nameof(ErrorReport)]; }
}
public string? GeneratedFilesOutputPath
{
set { _store[nameof(GeneratedFilesOutputPath)] = value; }
get { return (string?)_store[nameof(GeneratedFilesOutputPath)]; }
}
public bool GenerateFullPaths
{
set { _store[nameof(GenerateFullPaths)] = value; }
get { return _store.GetOrDefault(nameof(GenerateFullPaths), false); }
}
public string? ModuleAssemblyName
{
set { _store[nameof(ModuleAssemblyName)] = value; }
get { return (string?)_store[nameof(ModuleAssemblyName)]; }
}
public bool NoStandardLib
{
set { _store[nameof(NoStandardLib)] = value; }
get { return _store.GetOrDefault(nameof(NoStandardLib), false); }
}
public string? PdbFile
{
set { _store[nameof(PdbFile)] = value; }
get { return (string?)_store[nameof(PdbFile)]; }
}
/// <summary>
/// Name of the language passed to "/preferreduilang" compiler option.
/// </summary>
/// <remarks>
/// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting.
/// Otherwise, the value is passed to "/preferreduilang" as is.
/// </remarks>
public string? PreferredUILang
{
set { _store[nameof(PreferredUILang)] = value; }
get { return (string?)_store[nameof(PreferredUILang)]; }
}
public string? VsSessionGuid
{
set { _store[nameof(VsSessionGuid)] = value; }
get { return (string?)_store[nameof(VsSessionGuid)]; }
}
public bool UseHostCompilerIfAvailable
{
set { _store[nameof(UseHostCompilerIfAvailable)] = value; }
get { return _store.GetOrDefault(nameof(UseHostCompilerIfAvailable), false); }
}
public int WarningLevel
{
set { _store[nameof(WarningLevel)] = value; }
get { return _store.GetOrDefault(nameof(WarningLevel), 4); }
}
public string? WarningsAsErrors
{
set { _store[nameof(WarningsAsErrors)] = value; }
get { return (string?)_store[nameof(WarningsAsErrors)]; }
}
public string? WarningsNotAsErrors
{
set { _store[nameof(WarningsNotAsErrors)] = value; }
get { return (string?)_store[nameof(WarningsNotAsErrors)]; }
}
public string? Nullable
{
set
{
if (!string.IsNullOrEmpty(value))
{
_store[nameof(Nullable)] = value;
}
}
get { return (string?)_store[nameof(Nullable)]; }
}
#endregion
#region Tool Members
// Same separators as those used by Process.OutputDataReceived to maintain consistency between csc and VBCSCompiler
private static readonly string[] s_separators = { "\r\n", "\r", "\n" };
private protected override void LogCompilerOutput(string output, MessageImportance messageImportance)
{
var lines = output.Split(s_separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogMessageFromText(trimmedMessage, messageImportance);
}
}
}
/// <summary>
/// Return the name of the tool to execute.
/// </summary>
protected override string ToolNameWithoutExtension
{
get
{
return "csc";
}
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendSwitchIfNotNull("/lib:", AdditionalLibPaths, ",");
commandLine.AppendPlusOrMinusSwitch("/unsafe", _store, nameof(AllowUnsafeBlocks));
commandLine.AppendPlusOrMinusSwitch("/checked", _store, nameof(CheckForOverflowUnderflow));
commandLine.AppendSwitchWithSplitting("/nowarn:", DisabledWarnings, ",", ';', ',');
commandLine.AppendSwitchIfNotNull("/generatedfilesout:", GeneratedFilesOutputPath);
commandLine.AppendWhenTrue("/fullpaths", _store, nameof(GenerateFullPaths));
commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", ModuleAssemblyName);
commandLine.AppendSwitchIfNotNull("/pdb:", PdbFile);
commandLine.AppendPlusOrMinusSwitch("/nostdlib", _store, nameof(NoStandardLib));
commandLine.AppendSwitchIfNotNull("/platform:", PlatformWith32BitPreference);
commandLine.AppendSwitchIfNotNull("/errorreport:", ErrorReport);
commandLine.AppendSwitchWithInteger("/warn:", _store, nameof(WarningLevel));
commandLine.AppendSwitchIfNotNull("/doc:", DocumentationFile);
commandLine.AppendSwitchIfNotNull("/baseaddress:", BaseAddress);
commandLine.AppendSwitchUnquotedIfNotNull("/define:", GetDefineConstantsSwitch(DefineConstants, Log));
commandLine.AppendSwitchIfNotNull("/win32res:", Win32Resource);
commandLine.AppendSwitchIfNotNull("/main:", MainEntryPoint);
commandLine.AppendSwitchIfNotNull("/appconfig:", ApplicationConfiguration);
commandLine.AppendWhenTrue("/errorendlocation", _store, nameof(ErrorEndLocation));
commandLine.AppendSwitchIfNotNull("/preferreduilang:", PreferredUILang);
commandLine.AppendPlusOrMinusSwitch("/highentropyva", _store, nameof(HighEntropyVA));
commandLine.AppendSwitchIfNotNull("/nullable:", Nullable);
commandLine.AppendWhenTrue("/nosdkpath", _store, nameof(DisableSdkPath));
// If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
bool designTime = false;
if (HostObject is ICscHostObject csHost)
{
designTime = csHost.IsDesignTime();
}
else if (HostObject != null)
{
throw new InvalidOperationException(string.Format(ErrorString.General_IncorrectHostObject, "Csc", "ICscHostObject"));
}
if (!designTime)
{
if (!string.IsNullOrWhiteSpace(VsSessionGuid))
{
commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", VsSessionGuid);
}
}
AddReferencesToCommandLine(commandLine, References);
base.AddResponseFileCommands(commandLine);
// This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
// Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
// and then any specific warnings that should be treated as errors should be specified with
// /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line
// does matter.
//
// Note that
// /warnaserror+
// is just shorthand for:
// /warnaserror+:<all possible warnings>
//
// Similarly,
// /warnaserror-
// is just shorthand for:
// /warnaserror-:<all possible warnings>
commandLine.AppendSwitchWithSplitting("/warnaserror+:", WarningsAsErrors, ",", ';', ',');
commandLine.AppendSwitchWithSplitting("/warnaserror-:", WarningsNotAsErrors, ",", ';', ',');
// It's a good idea for the response file to be the very last switch passed, just
// from a predictability perspective. It also solves the problem that a dogfooder
// ran into, which is described in an email thread attached to bug VSWhidbey 146883.
// See also bugs 177762 and 118307 for additional bugs related to response file position.
if (ResponseFiles != null)
{
foreach (ITaskItem response in ResponseFiles)
{
commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
}
}
}
#endregion
internal override RequestLanguage Language => RequestLanguage.CSharpCompile;
/// <summary>
/// The C# compiler (starting with Whidbey) supports assembly aliasing for references.
/// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc.
/// This method handles the necessary work of looking at the "Aliases" attribute on
/// the incoming "References" items, and making sure to generate the correct
/// command-line on csc.exe. The syntax for aliasing a reference is:
/// csc.exe /reference:Goo=System.Xml.dll
///
/// The "Aliases" attribute on the "References" items is actually a comma-separated
/// list of aliases, and if any of the aliases specified is the string "global",
/// then we add that reference to the command-line without an alias.
/// </summary>
internal static void AddReferencesToCommandLine(
CommandLineBuilderExtension commandLine,
ITaskItem[]? references,
bool isInteractive = false)
{
// If there were no references passed in, don't add any /reference: switches
// on the command-line.
if (references == null)
{
return;
}
// Loop through all the references passed in. We'll be adding separate
// /reference: switches for each reference, and in some cases even multiple
// /reference: switches per reference.
foreach (ITaskItem reference in references)
{
// See if there was an "Alias" attribute on the reference.
string aliasString = reference.GetMetadata("Aliases");
string switchName = "/reference:";
if (!isInteractive)
{
bool embed = Utilities.TryConvertItemMetadataToBool(reference,
"EmbedInteropTypes");
if (embed)
{
switchName = "/link:";
}
}
if (string.IsNullOrEmpty(aliasString))
{
// If there was no "Alias" attribute, just add this as a global reference.
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// If there was an "Alias" attribute, it contains a comma-separated list
// of aliases to use for this reference. For each one of those aliases,
// we're going to add a separate /reference: switch to the csc.exe
// command-line
string[] aliases = aliasString.Split(',');
foreach (string alias in aliases)
{
// Trim whitespace.
string trimmedAlias = alias.Trim();
if (alias.Length == 0)
{
continue;
}
// The alias should be a valid C# identifier. Therefore it cannot
// contain comma, space, semicolon, or double-quote. Let's check for
// the existence of those characters right here, and bail immediately
// if any are present. There are a whole bunch of other characters
// that are not allowed in a C# identifier, but we'll just let csc.exe
// error out on those. The ones we're checking for here are the ones
// that could seriously screw up the command-line parsing or could
// allow parameter injection.
if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1)
{
throw Utilities.GetLocalizedArgumentException(
ErrorString.Csc_AssemblyAliasContainsIllegalCharacters,
reference.ItemSpec,
trimmedAlias);
}
// The alias called "global" is special. It means that we don't
// give it an alias on the command-line.
if (string.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0)
{
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// We have a valid (and explicit) alias for this reference. Add
// it to the command-line using the syntax:
// /reference:Goo=System.Xml.dll
commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec);
}
}
}
}
}
/// <summary>
/// Old VS projects had some pretty messed-up looking values for the
/// "DefineConstants" property. It worked fine in the IDE, because it
/// effectively munged up the string so that it ended up being valid for
/// the compiler. We do the equivalent munging here now.
///
/// Basically, we take the incoming string, and split it on comma/semicolon/space.
/// Then we look at the resulting list of strings, and remove any that are
/// illegal identifiers, and pass the remaining ones through to the compiler.
///
/// Note that CSharp doesn't support assigning a value to the constants ... in
/// other words, a constant is either defined or not defined ... it can't have
/// an actual value.
/// </summary>
internal static string? GetDefineConstantsSwitch(string? originalDefineConstants, TaskLoggingHelper log)
{
if (originalDefineConstants == null)
{
return null;
}
StringBuilder finalDefineConstants = new StringBuilder();
// Split the incoming string on comma/semicolon/space.
string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' });
// Loop through all the parts, and for the ones that are legal C# identifiers,
// add them to the outgoing string.
foreach (string singleIdentifier in allIdentifiers)
{
if (UnicodeCharacterUtilities.IsValidIdentifier(singleIdentifier))
{
// Separate them with a semicolon if there's something already in
// the outgoing string.
if (finalDefineConstants.Length > 0)
{
finalDefineConstants.Append(";");
}
finalDefineConstants.Append(singleIdentifier);
}
else if (singleIdentifier.Length > 0)
{
log.LogWarningWithCodeFromResources("Csc_InvalidParameterWarning", "/define:", singleIdentifier);
}
}
if (finalDefineConstants.Length > 0)
{
return finalDefineConstants.ToString();
}
else
{
// We wouldn't want to pass in an empty /define: switch on the csc.exe command-line.
return null;
}
}
/// <summary>
/// This method will initialize the host compiler object with all the switches,
/// parameters, resources, references, sources, etc.
///
/// It returns true if everything went according to plan. It returns false if the
/// host compiler had a problem with one of the parameters that was passed in.
///
/// This method also sets the "this.HostCompilerSupportsAllParameters" property
/// accordingly.
///
/// Example:
/// If we attempted to pass in WarningLevel="9876", then this method would
/// set HostCompilerSupportsAllParameters=true, but it would give a
/// return value of "false". This is because the host compiler fully supports
/// the WarningLevel parameter, but 9876 happens to be an illegal value.
///
/// Example:
/// If we attempted to pass in NoConfig=false, then this method would set
/// HostCompilerSupportsAllParameters=false, because while this is a legal
/// thing for csc.exe, the IDE compiler cannot support it. In this situation
/// the return value will also be false.
/// </summary>
/// <owner>RGoel</owner>
private bool InitializeHostCompiler(ICscHostObject cscHostObject)
{
bool success;
HostCompilerSupportsAllParameters = UseHostCompilerIfAvailable;
string param = "Unknown";
try
{
// Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE.
CheckHostObjectSupport(param = nameof(LinkResources), cscHostObject.SetLinkResources(LinkResources));
CheckHostObjectSupport(param = nameof(References), cscHostObject.SetReferences(References));
CheckHostObjectSupport(param = nameof(Resources), cscHostObject.SetResources(Resources));
CheckHostObjectSupport(param = nameof(Sources), cscHostObject.SetSources(Sources));
// For host objects which support it, pass the list of analyzers.
IAnalyzerHostObject? analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers));
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
try
{
param = nameof(cscHostObject.BeginInitialization);
cscHostObject.BeginInitialization();
CheckHostObjectSupport(param = nameof(AdditionalLibPaths), cscHostObject.SetAdditionalLibPaths(AdditionalLibPaths));
CheckHostObjectSupport(param = nameof(AddModules), cscHostObject.SetAddModules(AddModules));
CheckHostObjectSupport(param = nameof(AllowUnsafeBlocks), cscHostObject.SetAllowUnsafeBlocks(AllowUnsafeBlocks));
CheckHostObjectSupport(param = nameof(BaseAddress), cscHostObject.SetBaseAddress(BaseAddress));
CheckHostObjectSupport(param = nameof(CheckForOverflowUnderflow), cscHostObject.SetCheckForOverflowUnderflow(CheckForOverflowUnderflow));
CheckHostObjectSupport(param = nameof(CodePage), cscHostObject.SetCodePage(CodePage));
// These two -- EmitDebugInformation and DebugType -- must go together, with DebugType
// getting set last, because it is more specific.
CheckHostObjectSupport(param = nameof(EmitDebugInformation), cscHostObject.SetEmitDebugInformation(EmitDebugInformation));
CheckHostObjectSupport(param = nameof(DebugType), cscHostObject.SetDebugType(DebugType));
CheckHostObjectSupport(param = nameof(DefineConstants), cscHostObject.SetDefineConstants(GetDefineConstantsSwitch(DefineConstants, Log)));
CheckHostObjectSupport(param = nameof(DelaySign), cscHostObject.SetDelaySign((_store["DelaySign"] != null), DelaySign));
CheckHostObjectSupport(param = nameof(DisabledWarnings), cscHostObject.SetDisabledWarnings(DisabledWarnings));
CheckHostObjectSupport(param = nameof(DocumentationFile), cscHostObject.SetDocumentationFile(DocumentationFile));
CheckHostObjectSupport(param = nameof(ErrorReport), cscHostObject.SetErrorReport(ErrorReport));
CheckHostObjectSupport(param = nameof(FileAlignment), cscHostObject.SetFileAlignment(FileAlignment));
CheckHostObjectSupport(param = nameof(GenerateFullPaths), cscHostObject.SetGenerateFullPaths(GenerateFullPaths));
CheckHostObjectSupport(param = nameof(KeyContainer), cscHostObject.SetKeyContainer(KeyContainer));
CheckHostObjectSupport(param = nameof(KeyFile), cscHostObject.SetKeyFile(KeyFile));
CheckHostObjectSupport(param = nameof(LangVersion), cscHostObject.SetLangVersion(LangVersion));
CheckHostObjectSupport(param = nameof(MainEntryPoint), cscHostObject.SetMainEntryPoint(TargetType, MainEntryPoint));
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), cscHostObject.SetModuleAssemblyName(ModuleAssemblyName));
CheckHostObjectSupport(param = nameof(NoConfig), cscHostObject.SetNoConfig(NoConfig));
CheckHostObjectSupport(param = nameof(NoStandardLib), cscHostObject.SetNoStandardLib(NoStandardLib));
CheckHostObjectSupport(param = nameof(Optimize), cscHostObject.SetOptimize(Optimize));
CheckHostObjectSupport(param = nameof(OutputAssembly), cscHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec));
CheckHostObjectSupport(param = nameof(PdbFile), cscHostObject.SetPdbFile(PdbFile));
// For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
ICscHostObject4? cscHostObject4 = cscHostObject as ICscHostObject4;
if (cscHostObject4 != null)
{
CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), cscHostObject4.SetPlatformWith32BitPreference(PlatformWith32BitPreference));
CheckHostObjectSupport(param = nameof(HighEntropyVA), cscHostObject4.SetHighEntropyVA(HighEntropyVA));
CheckHostObjectSupport(param = nameof(SubsystemVersion), cscHostObject4.SetSubsystemVersion(SubsystemVersion));
}
else
{
CheckHostObjectSupport(param = nameof(Platform), cscHostObject.SetPlatform(Platform));
}
// For host objects which support it, set the analyzer ruleset and additional files.
IAnalyzerHostObject? analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet));
CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles));
}
// For host objects which support it, set the analyzer config files and potential config files.
if (cscHostObject is IAnalyzerConfigFilesHostObject analyzerConfigFilesHostObject)
{
CheckHostObjectSupport(param = nameof(AnalyzerConfigFiles), analyzerConfigFilesHostObject.SetAnalyzerConfigFiles(AnalyzerConfigFiles));
CheckHostObjectSupport(param = nameof(PotentialAnalyzerConfigFiles), analyzerConfigFilesHostObject.SetPotentialAnalyzerConfigFiles(PotentialAnalyzerConfigFiles));
}
ICscHostObject5? cscHostObject5 = cscHostObject as ICscHostObject5;
if (cscHostObject5 != null)
{
CheckHostObjectSupport(param = nameof(ErrorLog), cscHostObject5.SetErrorLog(ErrorLog));
CheckHostObjectSupport(param = nameof(ReportAnalyzer), cscHostObject5.SetReportAnalyzer(ReportAnalyzer));
}
CheckHostObjectSupport(param = nameof(ResponseFiles), cscHostObject.SetResponseFiles(ResponseFiles));
CheckHostObjectSupport(param = nameof(TargetType), cscHostObject.SetTargetType(TargetType));
CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), cscHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningLevel), cscHostObject.SetWarningLevel(WarningLevel));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsAsErrors), cscHostObject.SetWarningsAsErrors(WarningsAsErrors));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), cscHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors));
CheckHostObjectSupport(param = nameof(Win32Icon), cscHostObject.SetWin32Icon(Win32Icon));
// In order to maintain compatibility with previous host compilers, we must
// light-up for ICscHostObject2/ICscHostObject3
if (cscHostObject is ICscHostObject2)
{
ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject;
CheckHostObjectSupport(param = nameof(Win32Manifest), cscHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest)));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(Win32Manifest))
{
CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false);
}
}
// This must come after Win32Manifest
CheckHostObjectSupport(param = nameof(Win32Resource), cscHostObject.SetWin32Resource(Win32Resource));
if (cscHostObject is ICscHostObject3)
{
ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject;
CheckHostObjectSupport(param = nameof(ApplicationConfiguration), cscHostObject3.SetApplicationConfiguration(ApplicationConfiguration));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(ApplicationConfiguration))
{
CheckHostObjectSupport(nameof(ApplicationConfiguration), resultFromHostObjectSetOperation: false);
}
}
InitializeHostObjectSupportForNewSwitches(cscHostObject, ref param);
// If we have been given a property value that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler.
// Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
// Explicitly specified name of current locale is also supported, since it is effectively a no-op.
// Other options are not supported since in-proc compiler always uses current locale.
if (!string.IsNullOrEmpty(PreferredUILang) && !string.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
{
CheckHostObjectSupport(nameof(PreferredUILang), resultFromHostObjectSetOperation: false);
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
finally
{
int errorCode;
string errorMessage;
success = cscHostObject.EndInitialization(out errorMessage, out errorCode);
if (HostCompilerSupportsAllParameters)
{
// If the host compiler doesn't support everything we need, we're going to end up
// shelling out to the command-line compiler anyway. That means the command-line
// compiler will log the error. So here, we only log the error if we would've
// tried to use the host compiler.
// If EndInitialization returns false, then there was an error. If EndInitialization was
// successful, but there is a valid 'errorMessage,' interpret it as a warning.
if (!success)
{
Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
else if (errorMessage != null && errorMessage.Length > 0)
{
Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
}
}
return (success);
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns one of the following values to indicate what the next action should be:
/// UseHostObjectToExecute Host compiler exists and was initialized.
/// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate.
/// NoActionReturnSuccess Host compiler was already up-to-date, and we're done.
/// NoActionReturnFailure Bad parameters were passed into the task.
/// </summary>
/// <owner>RGoel</owner>
protected override HostObjectInitializationStatus InitializeHostObject()
{
if (HostObject != null)
{
// When the host object was passed into the task, it was passed in as a generic
// "Object" (because ITask interface obviously can't have any Csc-specific stuff
// in it, and each task is going to want to communicate with its host in a unique
// way). Now we cast it to the specific type that the Csc task expects. If the
// host object does not match this type, the host passed in an invalid host object
// to Csc, and we error out.
// NOTE: For compat reasons this must remain ICscHostObject
// we can dynamically test for smarter interfaces later..
if (HostObject is ICscHostObject hostObjectCOM)
{
using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(hostObjectCOM))
{
ICscHostObject cscHostObject = hostObject.RCW;
bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject);
// If we're currently only in design-time (as opposed to build-time),
// then we're done. We've initialized the host compiler as best we
// can, and we certainly don't want to actually do the final compile.
// So return true, saying we're done and successful.
if (cscHostObject.IsDesignTime())
{
// If we are design-time then we do not want to continue the build at
// this time.
return hostObjectSuccessfullyInitialized ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.NoActionReturnFailure;
}
if (!this.HostCompilerSupportsAllParameters)
{
// Since the host compiler has refused to take on the responsibility for this compilation,
// we're about to shell out to the command-line compiler to handle it. If some of the
// references don't exist on disk, we know the command-line compiler will fail, so save
// the trouble, and just throw a consistent error ourselves. This allows us to give
// more information than the compiler would, and also make things consistent across
// Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3).
// This suite behaves differently in localized builds than on English builds because
// VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
if (!CheckAllReferencesExistOnDisk())
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
// The host compiler doesn't support some of the switches/parameters
// being passed to it. Therefore, we resort to using the command-line compiler
// in this case.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
// Ok, by now we validated that the host object supports the necessary switches
// and parameters. Last thing to check is whether the host object is up to date,
// and in that case, we will inform the caller that no further action is necessary.
if (hostObjectSuccessfullyInitialized)
{
return cscHostObject.IsUpToDate() ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.UseHostObjectToExecute;
}
else
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
}
}
else
{
Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Csc", "ICscHostObject");
}
}
// No appropriate host object was found.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns true if the compilation succeeded, otherwise false.
/// </summary>
/// <owner>RGoel</owner>
protected override bool CallHostObjectToExecute()
{
Debug.Assert(HostObject != null, "We should not be here if the host object has not been set.");
ICscHostObject? cscHostObject = HostObject as ICscHostObject;
RoslynDebug.Assert(cscHostObject != null, "Wrong kind of host object passed in!");
return cscHostObject.Compile();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Roslyn.Utilities;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines the "Csc" XMake task, which enables building assemblies from C#
/// source files by invoking the C# compiler. This is the new Roslyn XMake task,
/// meaning that the code is compiled by using the Roslyn compiler server, rather
/// than csc.exe. The two should be functionally identical, but the compiler server
/// should be significantly faster with larger projects and have a smaller memory
/// footprint.
/// </summary>
public class Csc : ManagedCompiler
{
#region Properties
// Please keep these alphabetized. These are the parameters specific to Csc. The
// ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is
// the base class.
public bool AllowUnsafeBlocks
{
set { _store[nameof(AllowUnsafeBlocks)] = value; }
get { return _store.GetOrDefault(nameof(AllowUnsafeBlocks), false); }
}
public string? ApplicationConfiguration
{
set { _store[nameof(ApplicationConfiguration)] = value; }
get { return (string?)_store[nameof(ApplicationConfiguration)]; }
}
public string? BaseAddress
{
set { _store[nameof(BaseAddress)] = value; }
get { return (string?)_store[nameof(BaseAddress)]; }
}
public bool CheckForOverflowUnderflow
{
set { _store[nameof(CheckForOverflowUnderflow)] = value; }
get { return _store.GetOrDefault(nameof(CheckForOverflowUnderflow), false); }
}
public string? DocumentationFile
{
set { _store[nameof(DocumentationFile)] = value; }
get { return (string?)_store[nameof(DocumentationFile)]; }
}
public string? DisabledWarnings
{
set { _store[nameof(DisabledWarnings)] = value; }
get { return (string?)_store[nameof(DisabledWarnings)]; }
}
public bool DisableSdkPath
{
set { _store[nameof(DisableSdkPath)] = value; }
get { return _store.GetOrDefault(nameof(DisableSdkPath), false); }
}
public bool ErrorEndLocation
{
set { _store[nameof(ErrorEndLocation)] = value; }
get { return _store.GetOrDefault(nameof(ErrorEndLocation), false); }
}
public string? ErrorReport
{
set { _store[nameof(ErrorReport)] = value; }
get { return (string?)_store[nameof(ErrorReport)]; }
}
public string? GeneratedFilesOutputPath
{
set { _store[nameof(GeneratedFilesOutputPath)] = value; }
get { return (string?)_store[nameof(GeneratedFilesOutputPath)]; }
}
public bool GenerateFullPaths
{
set { _store[nameof(GenerateFullPaths)] = value; }
get { return _store.GetOrDefault(nameof(GenerateFullPaths), false); }
}
public string? ModuleAssemblyName
{
set { _store[nameof(ModuleAssemblyName)] = value; }
get { return (string?)_store[nameof(ModuleAssemblyName)]; }
}
public bool NoStandardLib
{
set { _store[nameof(NoStandardLib)] = value; }
get { return _store.GetOrDefault(nameof(NoStandardLib), false); }
}
public string? PdbFile
{
set { _store[nameof(PdbFile)] = value; }
get { return (string?)_store[nameof(PdbFile)]; }
}
/// <summary>
/// Name of the language passed to "/preferreduilang" compiler option.
/// </summary>
/// <remarks>
/// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting.
/// Otherwise, the value is passed to "/preferreduilang" as is.
/// </remarks>
public string? PreferredUILang
{
set { _store[nameof(PreferredUILang)] = value; }
get { return (string?)_store[nameof(PreferredUILang)]; }
}
public string? VsSessionGuid
{
set { _store[nameof(VsSessionGuid)] = value; }
get { return (string?)_store[nameof(VsSessionGuid)]; }
}
public bool UseHostCompilerIfAvailable
{
set { _store[nameof(UseHostCompilerIfAvailable)] = value; }
get { return _store.GetOrDefault(nameof(UseHostCompilerIfAvailable), false); }
}
public int WarningLevel
{
set { _store[nameof(WarningLevel)] = value; }
get { return _store.GetOrDefault(nameof(WarningLevel), 4); }
}
public string? WarningsAsErrors
{
set { _store[nameof(WarningsAsErrors)] = value; }
get { return (string?)_store[nameof(WarningsAsErrors)]; }
}
public string? WarningsNotAsErrors
{
set { _store[nameof(WarningsNotAsErrors)] = value; }
get { return (string?)_store[nameof(WarningsNotAsErrors)]; }
}
public string? Nullable
{
set
{
if (!string.IsNullOrEmpty(value))
{
_store[nameof(Nullable)] = value;
}
}
get { return (string?)_store[nameof(Nullable)]; }
}
#endregion
#region Tool Members
// Same separators as those used by Process.OutputDataReceived to maintain consistency between csc and VBCSCompiler
private static readonly string[] s_separators = { "\r\n", "\r", "\n" };
private protected override void LogCompilerOutput(string output, MessageImportance messageImportance)
{
var lines = output.Split(s_separators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
string trimmedMessage = line.Trim();
if (trimmedMessage != "")
{
Log.LogMessageFromText(trimmedMessage, messageImportance);
}
}
}
/// <summary>
/// Return the name of the tool to execute.
/// </summary>
protected override string ToolNameWithoutExtension
{
get
{
return "csc";
}
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendSwitchIfNotNull("/lib:", AdditionalLibPaths, ",");
commandLine.AppendPlusOrMinusSwitch("/unsafe", _store, nameof(AllowUnsafeBlocks));
commandLine.AppendPlusOrMinusSwitch("/checked", _store, nameof(CheckForOverflowUnderflow));
commandLine.AppendSwitchWithSplitting("/nowarn:", DisabledWarnings, ",", ';', ',');
commandLine.AppendSwitchIfNotNull("/generatedfilesout:", GeneratedFilesOutputPath);
commandLine.AppendWhenTrue("/fullpaths", _store, nameof(GenerateFullPaths));
commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", ModuleAssemblyName);
commandLine.AppendSwitchIfNotNull("/pdb:", PdbFile);
commandLine.AppendPlusOrMinusSwitch("/nostdlib", _store, nameof(NoStandardLib));
commandLine.AppendSwitchIfNotNull("/platform:", PlatformWith32BitPreference);
commandLine.AppendSwitchIfNotNull("/errorreport:", ErrorReport);
commandLine.AppendSwitchWithInteger("/warn:", _store, nameof(WarningLevel));
commandLine.AppendSwitchIfNotNull("/doc:", DocumentationFile);
commandLine.AppendSwitchIfNotNull("/baseaddress:", BaseAddress);
commandLine.AppendSwitchUnquotedIfNotNull("/define:", GetDefineConstantsSwitch(DefineConstants, Log));
commandLine.AppendSwitchIfNotNull("/win32res:", Win32Resource);
commandLine.AppendSwitchIfNotNull("/main:", MainEntryPoint);
commandLine.AppendSwitchIfNotNull("/appconfig:", ApplicationConfiguration);
commandLine.AppendWhenTrue("/errorendlocation", _store, nameof(ErrorEndLocation));
commandLine.AppendSwitchIfNotNull("/preferreduilang:", PreferredUILang);
commandLine.AppendPlusOrMinusSwitch("/highentropyva", _store, nameof(HighEntropyVA));
commandLine.AppendSwitchIfNotNull("/nullable:", Nullable);
commandLine.AppendWhenTrue("/nosdkpath", _store, nameof(DisableSdkPath));
// If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid>
bool designTime = false;
if (HostObject is ICscHostObject csHost)
{
designTime = csHost.IsDesignTime();
}
else if (HostObject != null)
{
throw new InvalidOperationException(string.Format(ErrorString.General_IncorrectHostObject, "Csc", "ICscHostObject"));
}
if (!designTime)
{
if (!string.IsNullOrWhiteSpace(VsSessionGuid))
{
commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", VsSessionGuid);
}
}
AddReferencesToCommandLine(commandLine, References);
base.AddResponseFileCommands(commandLine);
// This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs).
// Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line,
// and then any specific warnings that should be treated as errors should be specified with
// /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line
// does matter.
//
// Note that
// /warnaserror+
// is just shorthand for:
// /warnaserror+:<all possible warnings>
//
// Similarly,
// /warnaserror-
// is just shorthand for:
// /warnaserror-:<all possible warnings>
commandLine.AppendSwitchWithSplitting("/warnaserror+:", WarningsAsErrors, ",", ';', ',');
commandLine.AppendSwitchWithSplitting("/warnaserror-:", WarningsNotAsErrors, ",", ';', ',');
// It's a good idea for the response file to be the very last switch passed, just
// from a predictability perspective. It also solves the problem that a dogfooder
// ran into, which is described in an email thread attached to bug VSWhidbey 146883.
// See also bugs 177762 and 118307 for additional bugs related to response file position.
if (ResponseFiles != null)
{
foreach (ITaskItem response in ResponseFiles)
{
commandLine.AppendSwitchIfNotNull("@", response.ItemSpec);
}
}
}
#endregion
internal override RequestLanguage Language => RequestLanguage.CSharpCompile;
/// <summary>
/// The C# compiler (starting with Whidbey) supports assembly aliasing for references.
/// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc.
/// This method handles the necessary work of looking at the "Aliases" attribute on
/// the incoming "References" items, and making sure to generate the correct
/// command-line on csc.exe. The syntax for aliasing a reference is:
/// csc.exe /reference:Goo=System.Xml.dll
///
/// The "Aliases" attribute on the "References" items is actually a comma-separated
/// list of aliases, and if any of the aliases specified is the string "global",
/// then we add that reference to the command-line without an alias.
/// </summary>
internal static void AddReferencesToCommandLine(
CommandLineBuilderExtension commandLine,
ITaskItem[]? references,
bool isInteractive = false)
{
// If there were no references passed in, don't add any /reference: switches
// on the command-line.
if (references == null)
{
return;
}
// Loop through all the references passed in. We'll be adding separate
// /reference: switches for each reference, and in some cases even multiple
// /reference: switches per reference.
foreach (ITaskItem reference in references)
{
// See if there was an "Alias" attribute on the reference.
string aliasString = reference.GetMetadata("Aliases");
string switchName = "/reference:";
if (!isInteractive)
{
bool embed = Utilities.TryConvertItemMetadataToBool(reference,
"EmbedInteropTypes");
if (embed)
{
switchName = "/link:";
}
}
if (string.IsNullOrEmpty(aliasString))
{
// If there was no "Alias" attribute, just add this as a global reference.
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// If there was an "Alias" attribute, it contains a comma-separated list
// of aliases to use for this reference. For each one of those aliases,
// we're going to add a separate /reference: switch to the csc.exe
// command-line
string[] aliases = aliasString.Split(',');
foreach (string alias in aliases)
{
// Trim whitespace.
string trimmedAlias = alias.Trim();
if (alias.Length == 0)
{
continue;
}
// The alias should be a valid C# identifier. Therefore it cannot
// contain comma, space, semicolon, or double-quote. Let's check for
// the existence of those characters right here, and bail immediately
// if any are present. There are a whole bunch of other characters
// that are not allowed in a C# identifier, but we'll just let csc.exe
// error out on those. The ones we're checking for here are the ones
// that could seriously screw up the command-line parsing or could
// allow parameter injection.
if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1)
{
throw Utilities.GetLocalizedArgumentException(
ErrorString.Csc_AssemblyAliasContainsIllegalCharacters,
reference.ItemSpec,
trimmedAlias);
}
// The alias called "global" is special. It means that we don't
// give it an alias on the command-line.
if (string.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0)
{
commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec);
}
else
{
// We have a valid (and explicit) alias for this reference. Add
// it to the command-line using the syntax:
// /reference:Goo=System.Xml.dll
commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec);
}
}
}
}
}
/// <summary>
/// Old VS projects had some pretty messed-up looking values for the
/// "DefineConstants" property. It worked fine in the IDE, because it
/// effectively munged up the string so that it ended up being valid for
/// the compiler. We do the equivalent munging here now.
///
/// Basically, we take the incoming string, and split it on comma/semicolon/space.
/// Then we look at the resulting list of strings, and remove any that are
/// illegal identifiers, and pass the remaining ones through to the compiler.
///
/// Note that CSharp doesn't support assigning a value to the constants ... in
/// other words, a constant is either defined or not defined ... it can't have
/// an actual value.
/// </summary>
internal static string? GetDefineConstantsSwitch(string? originalDefineConstants, TaskLoggingHelper log)
{
if (originalDefineConstants == null)
{
return null;
}
StringBuilder finalDefineConstants = new StringBuilder();
// Split the incoming string on comma/semicolon/space.
string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' });
// Loop through all the parts, and for the ones that are legal C# identifiers,
// add them to the outgoing string.
foreach (string singleIdentifier in allIdentifiers)
{
if (UnicodeCharacterUtilities.IsValidIdentifier(singleIdentifier))
{
// Separate them with a semicolon if there's something already in
// the outgoing string.
if (finalDefineConstants.Length > 0)
{
finalDefineConstants.Append(";");
}
finalDefineConstants.Append(singleIdentifier);
}
else if (singleIdentifier.Length > 0)
{
log.LogWarningWithCodeFromResources("Csc_InvalidParameterWarning", "/define:", singleIdentifier);
}
}
if (finalDefineConstants.Length > 0)
{
return finalDefineConstants.ToString();
}
else
{
// We wouldn't want to pass in an empty /define: switch on the csc.exe command-line.
return null;
}
}
/// <summary>
/// This method will initialize the host compiler object with all the switches,
/// parameters, resources, references, sources, etc.
///
/// It returns true if everything went according to plan. It returns false if the
/// host compiler had a problem with one of the parameters that was passed in.
///
/// This method also sets the "this.HostCompilerSupportsAllParameters" property
/// accordingly.
///
/// Example:
/// If we attempted to pass in WarningLevel="9876", then this method would
/// set HostCompilerSupportsAllParameters=true, but it would give a
/// return value of "false". This is because the host compiler fully supports
/// the WarningLevel parameter, but 9876 happens to be an illegal value.
///
/// Example:
/// If we attempted to pass in NoConfig=false, then this method would set
/// HostCompilerSupportsAllParameters=false, because while this is a legal
/// thing for csc.exe, the IDE compiler cannot support it. In this situation
/// the return value will also be false.
/// </summary>
/// <owner>RGoel</owner>
private bool InitializeHostCompiler(ICscHostObject cscHostObject)
{
bool success;
HostCompilerSupportsAllParameters = UseHostCompilerIfAvailable;
string param = "Unknown";
try
{
// Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE.
CheckHostObjectSupport(param = nameof(LinkResources), cscHostObject.SetLinkResources(LinkResources));
CheckHostObjectSupport(param = nameof(References), cscHostObject.SetReferences(References));
CheckHostObjectSupport(param = nameof(Resources), cscHostObject.SetResources(Resources));
CheckHostObjectSupport(param = nameof(Sources), cscHostObject.SetSources(Sources));
// For host objects which support it, pass the list of analyzers.
IAnalyzerHostObject? analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers));
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
try
{
param = nameof(cscHostObject.BeginInitialization);
cscHostObject.BeginInitialization();
CheckHostObjectSupport(param = nameof(AdditionalLibPaths), cscHostObject.SetAdditionalLibPaths(AdditionalLibPaths));
CheckHostObjectSupport(param = nameof(AddModules), cscHostObject.SetAddModules(AddModules));
CheckHostObjectSupport(param = nameof(AllowUnsafeBlocks), cscHostObject.SetAllowUnsafeBlocks(AllowUnsafeBlocks));
CheckHostObjectSupport(param = nameof(BaseAddress), cscHostObject.SetBaseAddress(BaseAddress));
CheckHostObjectSupport(param = nameof(CheckForOverflowUnderflow), cscHostObject.SetCheckForOverflowUnderflow(CheckForOverflowUnderflow));
CheckHostObjectSupport(param = nameof(CodePage), cscHostObject.SetCodePage(CodePage));
// These two -- EmitDebugInformation and DebugType -- must go together, with DebugType
// getting set last, because it is more specific.
CheckHostObjectSupport(param = nameof(EmitDebugInformation), cscHostObject.SetEmitDebugInformation(EmitDebugInformation));
CheckHostObjectSupport(param = nameof(DebugType), cscHostObject.SetDebugType(DebugType));
CheckHostObjectSupport(param = nameof(DefineConstants), cscHostObject.SetDefineConstants(GetDefineConstantsSwitch(DefineConstants, Log)));
CheckHostObjectSupport(param = nameof(DelaySign), cscHostObject.SetDelaySign((_store["DelaySign"] != null), DelaySign));
CheckHostObjectSupport(param = nameof(DisabledWarnings), cscHostObject.SetDisabledWarnings(DisabledWarnings));
CheckHostObjectSupport(param = nameof(DocumentationFile), cscHostObject.SetDocumentationFile(DocumentationFile));
CheckHostObjectSupport(param = nameof(ErrorReport), cscHostObject.SetErrorReport(ErrorReport));
CheckHostObjectSupport(param = nameof(FileAlignment), cscHostObject.SetFileAlignment(FileAlignment));
CheckHostObjectSupport(param = nameof(GenerateFullPaths), cscHostObject.SetGenerateFullPaths(GenerateFullPaths));
CheckHostObjectSupport(param = nameof(KeyContainer), cscHostObject.SetKeyContainer(KeyContainer));
CheckHostObjectSupport(param = nameof(KeyFile), cscHostObject.SetKeyFile(KeyFile));
CheckHostObjectSupport(param = nameof(LangVersion), cscHostObject.SetLangVersion(LangVersion));
CheckHostObjectSupport(param = nameof(MainEntryPoint), cscHostObject.SetMainEntryPoint(TargetType, MainEntryPoint));
CheckHostObjectSupport(param = nameof(ModuleAssemblyName), cscHostObject.SetModuleAssemblyName(ModuleAssemblyName));
CheckHostObjectSupport(param = nameof(NoConfig), cscHostObject.SetNoConfig(NoConfig));
CheckHostObjectSupport(param = nameof(NoStandardLib), cscHostObject.SetNoStandardLib(NoStandardLib));
CheckHostObjectSupport(param = nameof(Optimize), cscHostObject.SetOptimize(Optimize));
CheckHostObjectSupport(param = nameof(OutputAssembly), cscHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec));
CheckHostObjectSupport(param = nameof(PdbFile), cscHostObject.SetPdbFile(PdbFile));
// For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion
ICscHostObject4? cscHostObject4 = cscHostObject as ICscHostObject4;
if (cscHostObject4 != null)
{
CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), cscHostObject4.SetPlatformWith32BitPreference(PlatformWith32BitPreference));
CheckHostObjectSupport(param = nameof(HighEntropyVA), cscHostObject4.SetHighEntropyVA(HighEntropyVA));
CheckHostObjectSupport(param = nameof(SubsystemVersion), cscHostObject4.SetSubsystemVersion(SubsystemVersion));
}
else
{
CheckHostObjectSupport(param = nameof(Platform), cscHostObject.SetPlatform(Platform));
}
// For host objects which support it, set the analyzer ruleset and additional files.
IAnalyzerHostObject? analyzerHostObject = cscHostObject as IAnalyzerHostObject;
if (analyzerHostObject != null)
{
CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet));
CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles));
}
// For host objects which support it, set the analyzer config files and potential config files.
if (cscHostObject is IAnalyzerConfigFilesHostObject analyzerConfigFilesHostObject)
{
CheckHostObjectSupport(param = nameof(AnalyzerConfigFiles), analyzerConfigFilesHostObject.SetAnalyzerConfigFiles(AnalyzerConfigFiles));
CheckHostObjectSupport(param = nameof(PotentialAnalyzerConfigFiles), analyzerConfigFilesHostObject.SetPotentialAnalyzerConfigFiles(PotentialAnalyzerConfigFiles));
}
ICscHostObject5? cscHostObject5 = cscHostObject as ICscHostObject5;
if (cscHostObject5 != null)
{
CheckHostObjectSupport(param = nameof(ErrorLog), cscHostObject5.SetErrorLog(ErrorLog));
CheckHostObjectSupport(param = nameof(ReportAnalyzer), cscHostObject5.SetReportAnalyzer(ReportAnalyzer));
}
CheckHostObjectSupport(param = nameof(ResponseFiles), cscHostObject.SetResponseFiles(ResponseFiles));
CheckHostObjectSupport(param = nameof(TargetType), cscHostObject.SetTargetType(TargetType));
CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), cscHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors));
CheckHostObjectSupport(param = nameof(WarningLevel), cscHostObject.SetWarningLevel(WarningLevel));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsAsErrors), cscHostObject.SetWarningsAsErrors(WarningsAsErrors));
// This must come after TreatWarningsAsErrors.
CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), cscHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors));
CheckHostObjectSupport(param = nameof(Win32Icon), cscHostObject.SetWin32Icon(Win32Icon));
// In order to maintain compatibility with previous host compilers, we must
// light-up for ICscHostObject2/ICscHostObject3
if (cscHostObject is ICscHostObject2)
{
ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject;
CheckHostObjectSupport(param = nameof(Win32Manifest), cscHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest)));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(Win32Manifest))
{
CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false);
}
}
// This must come after Win32Manifest
CheckHostObjectSupport(param = nameof(Win32Resource), cscHostObject.SetWin32Resource(Win32Resource));
if (cscHostObject is ICscHostObject3)
{
ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject;
CheckHostObjectSupport(param = nameof(ApplicationConfiguration), cscHostObject3.SetApplicationConfiguration(ApplicationConfiguration));
}
else
{
// If we have been given a property that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler
if (!string.IsNullOrEmpty(ApplicationConfiguration))
{
CheckHostObjectSupport(nameof(ApplicationConfiguration), resultFromHostObjectSetOperation: false);
}
}
InitializeHostObjectSupportForNewSwitches(cscHostObject, ref param);
// If we have been given a property value that the host compiler doesn't support
// then we need to state that we are falling back to the command line compiler.
// Null is supported because it means that option should be omitted, and compiler default used - obviously always valid.
// Explicitly specified name of current locale is also supported, since it is effectively a no-op.
// Other options are not supported since in-proc compiler always uses current locale.
if (!string.IsNullOrEmpty(PreferredUILang) && !string.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase))
{
CheckHostObjectSupport(nameof(PreferredUILang), resultFromHostObjectSetOperation: false);
}
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message);
return false;
}
finally
{
int errorCode;
string errorMessage;
success = cscHostObject.EndInitialization(out errorMessage, out errorCode);
if (HostCompilerSupportsAllParameters)
{
// If the host compiler doesn't support everything we need, we're going to end up
// shelling out to the command-line compiler anyway. That means the command-line
// compiler will log the error. So here, we only log the error if we would've
// tried to use the host compiler.
// If EndInitialization returns false, then there was an error. If EndInitialization was
// successful, but there is a valid 'errorMessage,' interpret it as a warning.
if (!success)
{
Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
else if (errorMessage != null && errorMessage.Length > 0)
{
Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage);
}
}
}
return (success);
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns one of the following values to indicate what the next action should be:
/// UseHostObjectToExecute Host compiler exists and was initialized.
/// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate.
/// NoActionReturnSuccess Host compiler was already up-to-date, and we're done.
/// NoActionReturnFailure Bad parameters were passed into the task.
/// </summary>
/// <owner>RGoel</owner>
protected override HostObjectInitializationStatus InitializeHostObject()
{
if (HostObject != null)
{
// When the host object was passed into the task, it was passed in as a generic
// "Object" (because ITask interface obviously can't have any Csc-specific stuff
// in it, and each task is going to want to communicate with its host in a unique
// way). Now we cast it to the specific type that the Csc task expects. If the
// host object does not match this type, the host passed in an invalid host object
// to Csc, and we error out.
// NOTE: For compat reasons this must remain ICscHostObject
// we can dynamically test for smarter interfaces later..
if (HostObject is ICscHostObject hostObjectCOM)
{
using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(hostObjectCOM))
{
ICscHostObject cscHostObject = hostObject.RCW;
bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject);
// If we're currently only in design-time (as opposed to build-time),
// then we're done. We've initialized the host compiler as best we
// can, and we certainly don't want to actually do the final compile.
// So return true, saying we're done and successful.
if (cscHostObject.IsDesignTime())
{
// If we are design-time then we do not want to continue the build at
// this time.
return hostObjectSuccessfullyInitialized ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.NoActionReturnFailure;
}
if (!this.HostCompilerSupportsAllParameters)
{
// Since the host compiler has refused to take on the responsibility for this compilation,
// we're about to shell out to the command-line compiler to handle it. If some of the
// references don't exist on disk, we know the command-line compiler will fail, so save
// the trouble, and just throw a consistent error ourselves. This allows us to give
// more information than the compiler would, and also make things consistent across
// Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3).
// This suite behaves differently in localized builds than on English builds because
// VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it.
if (!CheckAllReferencesExistOnDisk())
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
// The host compiler doesn't support some of the switches/parameters
// being passed to it. Therefore, we resort to using the command-line compiler
// in this case.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
// Ok, by now we validated that the host object supports the necessary switches
// and parameters. Last thing to check is whether the host object is up to date,
// and in that case, we will inform the caller that no further action is necessary.
if (hostObjectSuccessfullyInitialized)
{
return cscHostObject.IsUpToDate() ?
HostObjectInitializationStatus.NoActionReturnSuccess :
HostObjectInitializationStatus.UseHostObjectToExecute;
}
else
{
return HostObjectInitializationStatus.NoActionReturnFailure;
}
}
}
else
{
Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Csc", "ICscHostObject");
}
}
// No appropriate host object was found.
UsedCommandLineTool = true;
return HostObjectInitializationStatus.UseAlternateToolToExecute;
}
/// <summary>
/// This method will get called during Execute() if a host object has been passed into the Csc
/// task. Returns true if the compilation succeeded, otherwise false.
/// </summary>
/// <owner>RGoel</owner>
protected override bool CallHostObjectToExecute()
{
Debug.Assert(HostObject != null, "We should not be here if the host object has not been set.");
ICscHostObject? cscHostObject = HostObject as ICscHostObject;
RoslynDebug.Assert(cscHostObject != null, "Wrong kind of host object passed in!");
return cscHostObject.Compile();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Syntax/Parsing/TypeArgumentListParsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TypeArgumentListParsingTests : ParsingTests
{
public TypeArgumentListParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestPredefinedType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<string, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestArrayType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<X[], IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestPredefinedPointerType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<int*, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PointerType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.AsteriskToken);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNonPredefinedPointerType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<X*, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.MultiplyExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.AsteriskToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestTwoItemTupleType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<(int, string), IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestComparisonToTuple()
{
UsingTree(@"
public class C
{
public static void Main()
{
XX X = new XX();
int a = 1, b = 2;
bool z = X < (a, b), w = false;
}
}
struct XX
{
public static bool operator <(XX x, (int a, int b) arg) => true;
public static bool operator >(XX x, (int a, int b) arg) => false;
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "X");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "a");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "b");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.BoolKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "z");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.CloseParenToken);
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "w");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.StructDeclaration);
{
N(SyntaxKind.StructKeyword);
N(SyntaxKind.IdentifierToken, "XX");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.BoolKeyword);
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.LessThanToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken, "arg");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.BoolKeyword);
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.GreaterThanToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken, "arg");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestOneItemTupleType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<(A), IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.CloseParenToken);
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestQualifiedName()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A.B, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestAliasName()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A::B, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.AliasQualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNullableTypeWithComma()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A?, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.NullableType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.QuestionToken);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNullableTypeWithGreaterThan()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A?>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.NullableType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.QuestionToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNotNullableType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A?
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
M(SyntaxKind.ColonToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestGenericArgWithComma()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<T<S>, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "T");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "S");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestGenericArgWithGreaterThan()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<T<S>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "S");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TypeArgumentListParsingTests : ParsingTests
{
public TypeArgumentListParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestPredefinedType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<string, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestArrayType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<X[], IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.ArrayType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.ArrayRankSpecifier);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.OmittedArraySizeExpression);
{
N(SyntaxKind.OmittedArraySizeExpressionToken);
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestPredefinedPointerType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<int*, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.PointerType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.AsteriskToken);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNonPredefinedPointerType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<X*, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.MultiplyExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.AsteriskToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestTwoItemTupleType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<(int, string), IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.CloseParenToken);
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestComparisonToTuple()
{
UsingTree(@"
public class C
{
public static void Main()
{
XX X = new XX();
int a = 1, b = 2;
bool z = X < (a, b), w = false;
}
}
struct XX
{
public static bool operator <(XX x, (int a, int b) arg) => true;
public static bool operator >(XX x, (int a, int b) arg) => false;
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "X");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "a");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "b");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.BoolKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "z");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.CloseParenToken);
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "w");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.StructDeclaration);
{
N(SyntaxKind.StructKeyword);
N(SyntaxKind.IdentifierToken, "XX");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.BoolKeyword);
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.LessThanToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken, "arg");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.BoolKeyword);
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.GreaterThanToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "XX");
}
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken, "arg");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestOneItemTupleType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<(A), IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.CloseParenToken);
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestQualifiedName()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A.B, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestAliasName()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A::B, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.AliasQualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.LessThanExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNullableTypeWithComma()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A?, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.NullableType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.QuestionToken);
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNullableTypeWithGreaterThan()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A?>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.NullableType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.QuestionToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestNotNullableType()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<A?
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
M(SyntaxKind.ColonToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestGenericArgWithComma()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<T<S>, IImmutableDictionary<X, Y>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "T");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "S");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IImmutableDictionary");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "X");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Y");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(19456, "https://github.com/dotnet/roslyn/issues/19456")]
public void TestGenericArgWithGreaterThan()
{
UsingTree(@"
class C
{
void M()
{
var added = ImmutableDictionary<T<S>>
ProjectChange = projectChange;
}
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "added");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ImmutableDictionary");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "S");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectChange");
}
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "projectChange");
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/Core/Analyzers/Helpers/DiagnosticHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class DiagnosticHelper
{
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
LocalizableString message;
if (messageArgs == null || messageArgs.Length == 0)
{
message = descriptor.MessageFormat;
}
else
{
message = new LocalizableStringWithArguments(descriptor.MessageFormat, messageArgs);
}
return CreateWithMessage(descriptor, location, effectiveSeverity, additionalLocations, properties, message);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
ImmutableDictionary<string, string>.Empty,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
properties,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// </param>
/// <param name="tagIndices">
/// a map of location tag to index in additional locations.
/// "AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer" for an example of usage.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
private static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
IDictionary<string, IEnumerable<int>> tagIndices,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
Contract.ThrowIfTrue(additionalLocations.IsEmpty());
Contract.ThrowIfTrue(tagIndices.IsEmpty());
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.AddRange(tagIndices.Select(kvp => new KeyValuePair<string, string>(kvp.Key, EncodeIndices(kvp.Value, additionalLocations.Count()))));
return Create(descriptor, location, effectiveSeverity, additionalLocations, properties, messageArgs);
static string EncodeIndices(IEnumerable<int> indices, int additionalLocationsLength)
{
// Ensure that the provided tag index is a valid index into additional locations.
Contract.ThrowIfFalse(indices.All(idx => idx >= 0 && idx < additionalLocationsLength));
using var stream = new MemoryStream();
var serializer = new DataContractJsonSerializer(typeof(IEnumerable<int>));
serializer.WriteObject(stream, indices);
var jsonBytes = stream.ToArray();
stream.Close();
return Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
}
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="message">Localizable message for the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithMessage(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
LocalizableString message)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
return Diagnostic.Create(
descriptor.Id,
descriptor.Category,
message,
effectiveSeverity.ToDiagnosticSeverity() ?? descriptor.DefaultSeverity,
descriptor.DefaultSeverity,
descriptor.IsEnabledByDefault,
warningLevel: effectiveSeverity.WithDefaultSeverity(descriptor.DefaultSeverity) == ReportDiagnostic.Error ? 0 : 1,
effectiveSeverity == ReportDiagnostic.Suppress,
descriptor.Title,
descriptor.Description,
descriptor.HelpLinkUri,
location,
additionalLocations,
descriptor.CustomTags,
properties);
}
public static string GetHelpLinkForDiagnosticId(string id)
{
if (id == "RE0001")
{
// TODO: Add documentation for Regex analyzer
// Tracked with https://github.com/dotnet/roslyn/issues/48530
return null;
}
Debug.Assert(id.StartsWith("IDE", StringComparison.Ordinal));
return $"https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/{id.ToLowerInvariant()}";
}
public sealed class LocalizableStringWithArguments : LocalizableString, IObjectWritable
{
private readonly LocalizableString _messageFormat;
private readonly string[] _formatArguments;
static LocalizableStringWithArguments()
=> ObjectBinder.RegisterTypeReader(typeof(LocalizableStringWithArguments), reader => new LocalizableStringWithArguments(reader));
public LocalizableStringWithArguments(LocalizableString messageFormat, params object[] formatArguments)
{
if (messageFormat == null)
{
throw new ArgumentNullException(nameof(messageFormat));
}
if (formatArguments == null)
{
throw new ArgumentNullException(nameof(formatArguments));
}
_messageFormat = messageFormat;
_formatArguments = new string[formatArguments.Length];
for (var i = 0; i < formatArguments.Length; i++)
{
_formatArguments[i] = $"{formatArguments[i]}";
}
}
private LocalizableStringWithArguments(ObjectReader reader)
{
_messageFormat = (LocalizableString)reader.ReadValue();
var length = reader.ReadInt32();
if (length == 0)
{
_formatArguments = Array.Empty<string>();
}
else
{
using var argumentsBuilderDisposer = ArrayBuilder<string>.GetInstance(length, out var argumentsBuilder);
for (var i = 0; i < length; i++)
{
argumentsBuilder.Add(reader.ReadString());
}
_formatArguments = argumentsBuilder.ToArray();
}
}
bool IObjectWritable.ShouldReuseInSerialization => false;
void IObjectWritable.WriteTo(ObjectWriter writer)
{
writer.WriteValue(_messageFormat);
var length = _formatArguments.Length;
writer.WriteInt32(length);
for (var i = 0; i < length; i++)
{
writer.WriteString(_formatArguments[i]);
}
}
protected override string GetText(IFormatProvider formatProvider)
{
var messageFormat = _messageFormat.ToString(formatProvider);
return messageFormat != null ?
(_formatArguments.Length > 0 ? string.Format(formatProvider, messageFormat, _formatArguments) : messageFormat) :
string.Empty;
}
protected override bool AreEqual(object other)
{
return other is LocalizableStringWithArguments otherResourceString &&
_messageFormat.Equals(otherResourceString._messageFormat) &&
_formatArguments.SequenceEqual(otherResourceString._formatArguments, (a, b) => a == b);
}
protected override int GetHash()
{
return Hash.Combine(
_messageFormat.GetHashCode(),
Hash.CombineValues(_formatArguments));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class DiagnosticHelper
{
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic Create(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
LocalizableString message;
if (messageArgs == null || messageArgs.Length == 0)
{
message = descriptor.MessageFormat;
}
else
{
message = new LocalizableStringWithArguments(descriptor.MessageFormat, messageArgs);
}
return CreateWithMessage(descriptor, location, effectiveSeverity, additionalLocations, properties, message);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
ImmutableDictionary<string, string>.Empty,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// These locations are joined with <paramref name="additionalUnnecessaryLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="additionalUnnecessaryLocations">
/// An optional set of additional locations indicating unnecessary code related to the diagnostic.
/// These locations are joined with <paramref name="additionalLocations"/> to produce the value for
/// <see cref="Diagnostic.AdditionalLocations"/>.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
ImmutableArray<Location> additionalLocations,
ImmutableArray<Location> additionalUnnecessaryLocations,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
if (additionalUnnecessaryLocations.IsEmpty)
{
return Create(descriptor, location, effectiveSeverity, additionalLocations, ImmutableDictionary<string, string>.Empty, messageArgs);
}
var tagIndices = ImmutableDictionary<string, IEnumerable<int>>.Empty
.Add(WellKnownDiagnosticTags.Unnecessary, Enumerable.Range(additionalLocations.Length, additionalUnnecessaryLocations.Length));
return CreateWithLocationTags(
descriptor,
location,
effectiveSeverity,
additionalLocations.AddRange(additionalUnnecessaryLocations),
tagIndices,
properties,
messageArgs);
}
/// <summary>
/// Create a diagnostic that adds properties specifying a tag for a set of locations.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// </param>
/// <param name="tagIndices">
/// a map of location tag to index in additional locations.
/// "AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer" for an example of usage.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer.
/// </param>
/// <param name="messageArgs">Arguments to the message of the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
private static Diagnostic CreateWithLocationTags(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
IDictionary<string, IEnumerable<int>> tagIndices,
ImmutableDictionary<string, string> properties,
params object[] messageArgs)
{
Contract.ThrowIfTrue(additionalLocations.IsEmpty());
Contract.ThrowIfTrue(tagIndices.IsEmpty());
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.AddRange(tagIndices.Select(kvp => new KeyValuePair<string, string>(kvp.Key, EncodeIndices(kvp.Value, additionalLocations.Count()))));
return Create(descriptor, location, effectiveSeverity, additionalLocations, properties, messageArgs);
static string EncodeIndices(IEnumerable<int> indices, int additionalLocationsLength)
{
// Ensure that the provided tag index is a valid index into additional locations.
Contract.ThrowIfFalse(indices.All(idx => idx >= 0 && idx < additionalLocationsLength));
using var stream = new MemoryStream();
var serializer = new DataContractJsonSerializer(typeof(IEnumerable<int>));
serializer.WriteObject(stream, indices);
var jsonBytes = stream.ToArray();
stream.Close();
return Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
}
}
/// <summary>
/// Creates a <see cref="Diagnostic"/> instance.
/// </summary>
/// <param name="descriptor">A <see cref="DiagnosticDescriptor"/> describing the diagnostic.</param>
/// <param name="location">An optional primary location of the diagnostic. If null, <see cref="Location"/> will return <see cref="Location.None"/>.</param>
/// <param name="effectiveSeverity">Effective severity of the diagnostic.</param>
/// <param name="additionalLocations">
/// An optional set of additional locations related to the diagnostic.
/// Typically, these are locations of other items referenced in the message.
/// If null, <see cref="Diagnostic.AdditionalLocations"/> will return an empty list.
/// </param>
/// <param name="properties">
/// An optional set of name-value pairs by means of which the analyzer that creates the diagnostic
/// can convey more detailed information to the fixer. If null, <see cref="Diagnostic.Properties"/> will return
/// <see cref="ImmutableDictionary{TKey, TValue}.Empty"/>.
/// </param>
/// <param name="message">Localizable message for the diagnostic.</param>
/// <returns>The <see cref="Diagnostic"/> instance.</returns>
public static Diagnostic CreateWithMessage(
DiagnosticDescriptor descriptor,
Location location,
ReportDiagnostic effectiveSeverity,
IEnumerable<Location> additionalLocations,
ImmutableDictionary<string, string> properties,
LocalizableString message)
{
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
return Diagnostic.Create(
descriptor.Id,
descriptor.Category,
message,
effectiveSeverity.ToDiagnosticSeverity() ?? descriptor.DefaultSeverity,
descriptor.DefaultSeverity,
descriptor.IsEnabledByDefault,
warningLevel: effectiveSeverity.WithDefaultSeverity(descriptor.DefaultSeverity) == ReportDiagnostic.Error ? 0 : 1,
effectiveSeverity == ReportDiagnostic.Suppress,
descriptor.Title,
descriptor.Description,
descriptor.HelpLinkUri,
location,
additionalLocations,
descriptor.CustomTags,
properties);
}
public static string GetHelpLinkForDiagnosticId(string id)
{
if (id == "RE0001")
{
// TODO: Add documentation for Regex analyzer
// Tracked with https://github.com/dotnet/roslyn/issues/48530
return null;
}
Debug.Assert(id.StartsWith("IDE", StringComparison.Ordinal));
return $"https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/{id.ToLowerInvariant()}";
}
public sealed class LocalizableStringWithArguments : LocalizableString, IObjectWritable
{
private readonly LocalizableString _messageFormat;
private readonly string[] _formatArguments;
static LocalizableStringWithArguments()
=> ObjectBinder.RegisterTypeReader(typeof(LocalizableStringWithArguments), reader => new LocalizableStringWithArguments(reader));
public LocalizableStringWithArguments(LocalizableString messageFormat, params object[] formatArguments)
{
if (messageFormat == null)
{
throw new ArgumentNullException(nameof(messageFormat));
}
if (formatArguments == null)
{
throw new ArgumentNullException(nameof(formatArguments));
}
_messageFormat = messageFormat;
_formatArguments = new string[formatArguments.Length];
for (var i = 0; i < formatArguments.Length; i++)
{
_formatArguments[i] = $"{formatArguments[i]}";
}
}
private LocalizableStringWithArguments(ObjectReader reader)
{
_messageFormat = (LocalizableString)reader.ReadValue();
var length = reader.ReadInt32();
if (length == 0)
{
_formatArguments = Array.Empty<string>();
}
else
{
using var argumentsBuilderDisposer = ArrayBuilder<string>.GetInstance(length, out var argumentsBuilder);
for (var i = 0; i < length; i++)
{
argumentsBuilder.Add(reader.ReadString());
}
_formatArguments = argumentsBuilder.ToArray();
}
}
bool IObjectWritable.ShouldReuseInSerialization => false;
void IObjectWritable.WriteTo(ObjectWriter writer)
{
writer.WriteValue(_messageFormat);
var length = _formatArguments.Length;
writer.WriteInt32(length);
for (var i = 0; i < length; i++)
{
writer.WriteString(_formatArguments[i]);
}
}
protected override string GetText(IFormatProvider formatProvider)
{
var messageFormat = _messageFormat.ToString(formatProvider);
return messageFormat != null ?
(_formatArguments.Length > 0 ? string.Format(formatProvider, messageFormat, _formatArguments) : messageFormat) :
string.Empty;
}
protected override bool AreEqual(object other)
{
return other is LocalizableStringWithArguments otherResourceString &&
_messageFormat.Equals(otherResourceString._messageFormat) &&
_formatArguments.SequenceEqual(otherResourceString._formatArguments, (a, b) => a == b);
}
protected override int GetHash()
{
return Hash.Combine(
_messageFormat.GetHashCode(),
Hash.CombineValues(_formatArguments));
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Inherit this type to provide source code refactorings.
/// Remember to use <see cref="ExportCodeRefactoringProviderAttribute"/> so the host environment can offer your refactorings in a UI.
/// </summary>
public abstract class CodeRefactoringProvider
{
/// <summary>
/// Computes one or more refactorings for the specified <see cref="CodeRefactoringContext"/>.
/// </summary>
public abstract Task ComputeRefactoringsAsync(CodeRefactoringContext context);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Inherit this type to provide source code refactorings.
/// Remember to use <see cref="ExportCodeRefactoringProviderAttribute"/> so the host environment can offer your refactorings in a UI.
/// </summary>
public abstract class CodeRefactoringProvider
{
/// <summary>
/// Computes one or more refactorings for the specified <see cref="CodeRefactoringContext"/>.
/// </summary>
public abstract Task ComputeRefactoringsAsync(CodeRefactoringContext context);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelGetSemanticInfoTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
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.Test.Utilities;
using Xunit;
// Note: the easiest way to create new unit tests that use GetSemanticInfo
// is to use the SemanticInfo unit test generate in Editor Test App.
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
using Utils = CompilationUtils;
public class SemanticModelGetSemanticInfoTests : SemanticModelTestBase
{
[Fact]
public void FailedOverloadResolution()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
int i = 8;
int j = i + q;
/*<bind>*/X.f/*</bind>*/(""hello"");
}
}
class X
{
public static void f() { }
public static void f(int i) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void X.f()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("void X.f(System.Int32 i)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void X.f()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void X.f(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SimpleGenericType()
{
string sourceCode = @"
using System;
class Program
{
/*<bind>*/K<int>/*</bind>*/ f;
}
class K<T>
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("K<System.Int32>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity1()
{
string sourceCode = @"
using System;
class Program
{
/*<bind>*/K<int, string>/*</bind>*/ f;
}
class K<T>
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity2()
{
string sourceCode = @"
using System;
class Program
{
/*<bind>*/K/*</bind>*/ f;
}
class K<T>
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity3()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
/*<bind>*/K<int, int>/*</bind>*/.f();
}
}
class K<T>
{
void f() { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity4()
{
string sourceCode = @"
using System;
class Program
{
static K Main()
{
/*<bind>*/K/*</bind>*/.f();
}
}
class K<T>
{
void f() { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NotInvocable()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
K./*<bind>*/f/*</bind>*/();
}
}
class K
{
public int f;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotInvocable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleField()
{
string sourceCode = @"
class Program
{
static void Main()
{
K./*<bind>*/f/*</bind>*/ = 3;
}
}
class K
{
private int f;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleFieldAssignment()
{
string sourceCode =
@"class A
{
string F;
}
class B
{
static void M(A a)
{
/*<bind>*/a.F/*</bind>*/ = string.Empty;
}
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
var symbol = semanticInfo.Symbol;
Assert.Null(symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("System.String A.F", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, symbol.Kind);
}
[WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")]
[Fact]
public void InaccessibleBaseClassConstructor01()
{
string sourceCode = @"
namespace Test
{
public class Base
{
protected Base() { }
}
public class Derived : Base
{
void M()
{
Base b = /*<bind>*/new Base()/*</bind>*/;
}
}
}";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Test.Base..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
}
[WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")]
[Fact]
public void InaccessibleBaseClassConstructor02()
{
string sourceCode = @"
namespace Test
{
public class Base
{
protected Base() { }
}
public class Derived : Base
{
void M()
{
Base b = new /*<bind>*/Base/*</bind>*/();
}
}
}";
var semanticInfo = GetSemanticInfoForTest<NameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal("Test.Base", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MemberGroup.Length);
}
[Fact]
public void InaccessibleFieldMethodArg()
{
string sourceCode =
@"class A
{
string F;
}
class B
{
static void M(A a)
{
M(/*<bind>*/a.F/*</bind>*/);
}
static void M(string s) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
var symbol = semanticInfo.Symbol;
Assert.Null(symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("System.String A.F", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, symbol.Kind);
}
[Fact]
public void TypeNotAVariable()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
/*<bind>*/K/*</bind>*/ = 12;
}
}
class K
{
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleType1()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
/*<bind>*/K.J/*</bind>*/ = v;
}
}
class K
{
protected class J { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K.J", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguousTypesBetweenUsings1()
{
string sourceCode = @"
using System;
using N1;
using N2;
class Program
{
/*<bind>*/A/*</bind>*/ field;
}
namespace N1
{
class A { }
}
namespace N2
{
class A { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguousTypesBetweenUsings2()
{
string sourceCode = @"
using System;
using N1;
using N2;
class Program
{
void f()
{
/*<bind>*/A/*</bind>*/.g();
}
}
namespace N1
{
class A { }
}
namespace N2
{
class A { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguousTypesBetweenUsings3()
{
string sourceCode = @"
using System;
using N1;
using N2;
class Program
{
void f()
{
/*<bind>*/A<int>/*</bind>*/.g();
}
}
namespace N1
{
class A<T> { }
}
namespace N2
{
class A<U> { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.A<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("N1.A<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.A<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("N2.A<U>", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguityBetweenInterfaceMembers()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
interface I1
{
public int P { get; }
}
interface I2
{
public string P { get; }
}
interface I3 : I1, I2
{ }
public class Class1
{
void f()
{
I3 x = null;
int o = x./*<bind>*/P/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("I1.P", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 I1.P { get; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal("System.String I2.P { get; }", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Alias1()
{
string sourceCode = @"
using O = System.Object;
partial class A : /*<bind>*/O/*</bind>*/ {}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Alias2()
{
string sourceCode = @"
using O = System.Object;
partial class A {
void f()
{
/*<bind>*/O/*</bind>*/.ReferenceEquals(null, null);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(539002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539002")]
[Fact]
public void IncompleteGenericMethodCall()
{
string sourceCode = @"
class Array
{
public static void Find<T>(T t) { }
}
class C
{
static void Main()
{
/*<bind>*/Array.Find<int>/*</bind>*/(
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void IncompleteExtensionMethodCall()
{
string sourceCode =
@"interface I<T> { }
class A { }
class B : A { }
class C
{
static void M(A a)
{
/*<bind>*/a.M/*</bind>*/(
}
}
static class S
{
internal static void M(this object o, int x) { }
internal static void M(this A a, int x, int y) { }
internal static void M(this B b) { }
internal static void M(this string s) { }
internal static void M<T>(this T t, object o) { }
internal static void M<T>(this T[] t) { }
internal static void M<T, U>(this T x, I<T> y, U z) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void object.M(int x)",
"void A.M(int x, int y)",
"void A.M<A>(object o)",
"void A.M<A, U>(I<A> y, U z)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void object.M(int x)",
"void A.M(int x, int y)",
"void A.M<A>(object o)",
"void A.M<A, U>(I<A> y, U z)");
Utils.CheckReducedExtensionMethod(semanticInfo.MethodGroup[3].GetSymbol(),
"void A.M<A, U>(I<A> y, U z)",
"void S.M<T, U>(T x, I<T> y, U z)",
"void T.M<T, U>(I<T> y, U z)",
"void S.M<T, U>(T x, I<T> y, U z)");
}
[Fact]
public void IncompleteExtensionMethodCallBadThisType()
{
string sourceCode =
@"interface I<T> { }
class B
{
static void M(I<A> a)
{
/*<bind>*/a.M/*</bind>*/(
}
}
static class S
{
internal static void M(this object o) { }
internal static void M<T>(this T t, object o) { }
internal static void M<T>(this T[] t) { }
internal static void M<T, U>(this I<T> x, I<T> y, U z) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void object.M()",
"void I<A>.M<I<A>>(object o)",
"void I<A>.M<A, U>(I<A> y, U z)");
}
[WorkItem(541141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541141")]
[Fact]
public void IncompleteGenericExtensionMethodCall()
{
string sourceCode =
@"using System.Linq;
class C
{
static void M(double[] a)
{
/*<bind>*/a.Where/*</bind>*/(
}
}";
var compilation = CreateCompilation(source: sourceCode);
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, bool> predicate)",
"IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, int, bool> predicate)");
}
[WorkItem(541349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541349")]
[Fact]
public void GenericExtensionMethodCallExplicitTypeArgs()
{
string sourceCode =
@"interface I<T> { }
class C
{
static void M(object o)
{
/*<bind>*/o.E<int>/*</bind>*/();
}
}
static class S
{
internal static void E(this object x, object y) { }
internal static void E<T>(this object o) { }
internal static void E<T>(this object o, T t) { }
internal static void E<T>(this I<T> t) { }
internal static void E<T, U>(this I<T> t) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Utils.CheckSymbol(semanticInfo.Symbol,
"void object.E<int>()");
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void object.E<int>()",
"void object.E<int>(int t)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
}
[Fact]
public void GenericExtensionMethodCallExplicitTypeArgsOfT()
{
string sourceCode =
@"interface I<T> { }
class C
{
static void M<T, U>(T t, U u)
{
/*<bind>*/t.E<T, U>/*</bind>*/(u);
}
}
static class S
{
internal static void E(this object x, object y) { }
internal static void E<T>(this object o) { }
internal static void E<T, U>(this T t, U u) { }
internal static void E<T, U>(this I<T> t, U u) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void T.E<T, U>(U u)");
}
[WorkItem(541297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541297")]
[Fact]
public void GenericExtensionMethodCall()
{
// Single applicable overload with valid argument.
var semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
/*<bind>*/s.E(s)/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, object y) { }
internal static void E<T, U>(this T x, U y) { }
}");
Utils.CheckSymbol(semanticInfo.Symbol,
"void string.E<string, string>(string y)");
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Multiple applicable overloads with valid arguments.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s, object o)
{
/*<bind>*/s.E(s, o)/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this object x, T y, object z) { }
internal static void E<T, U>(this T x, object y, U z) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void object.E<string>(string y, object z)",
"void string.E<string, object>(object y, object z)");
// Multiple applicable overloads with error argument.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
/*<bind>*/s.E(t, s)/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, T y, object z) { }
internal static void E<T, U>(this T x, string y, U z) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void string.E<string>(string y, object z)",
"void string.E<string, string>(string y, string z)");
// Multiple overloads but all inaccessible.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
/*<bind>*/s.E()/*</bind>*/;
}
}
static class S
{
static void E(this string x) { }
static void E<T>(this T x) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols
/* no candidates */
);
}
[Fact]
public void GenericExtensionDelegateMethod()
{
// Single applicable overload.
var semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
System.Action<string> a = /*<bind>*/s.E/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, T y) { }
internal static void E<T>(this object x, T y) { }
}");
Utils.CheckSymbol(semanticInfo.Symbol,
"void string.E<string>(string y)");
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void string.E<string>(string y)",
"void object.E<T>(T y)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Multiple applicable overloads.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
System.Action<string> a = /*<bind>*/s.E/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, T y) { }
internal static void E<T, U>(this T x, U y) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void string.E<string>(string y)",
"void string.E<string, U>(U y)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void string.E<string>(string y)",
"void string.E<string, U>(U y)");
}
/// <summary>
/// Overloads from different scopes should
/// be included in method group.
/// </summary>
[WorkItem(541890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541890")]
[Fact]
public void IncompleteExtensionOverloadedDifferentScopes()
{
// Instance methods and extension method (implicit instance).
var sourceCode =
@"class C
{
void M()
{
/*<bind>*/F/*</bind>*/(
}
void F(int x) { }
void F(object x, object y) { }
}
static class E
{
internal static void F(this object x, object y) { }
}";
var compilation = (Compilation)CreateCompilation(source: sourceCode);
var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
var symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)");
symbols = model.LookupSymbols(expr.SpanStart, container: null, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)",
"void object.F(object y)");
// Instance methods and extension method (explicit instance).
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F/*</bind>*/(
}
void F(int x) { }
void F(object x, object y) { }
}
static class E
{
internal static void F(this object x, object y) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)",
"void object.F(object y)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)",
"void object.F(object y)");
// Applicable instance method and inapplicable extension method.
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F<string>/*</bind>*/(
}
void F<T>(T t) { }
}
static class E
{
internal static void F(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F<string>(string t)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F<T>(T t)",
"void object.F()");
// Inaccessible instance method and accessible extension method.
sourceCode =
@"class A
{
void F() { }
}
class B : A
{
static void M(A a)
{
/*<bind>*/a.F/*</bind>*/(
}
}
static class E
{
internal static void F(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void object.F()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F()");
// Inapplicable instance method and applicable extension method.
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F<string>/*</bind>*/(
}
void F(object o) { }
}
static class E
{
internal static void F<T>(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void object.F<string>()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(object o)",
"void object.F<T>()");
// Viable instance and extension methods, binding to extension method.
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F/*</bind>*/();
}
void F(object o) { }
}
static class E
{
internal static void F(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(object o)",
"void object.F()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(object o)",
"void object.F()");
// Applicable and inaccessible extension methods.
sourceCode =
@"class C
{
void M(string s)
{
/*<bind>*/s.F<string>/*</bind>*/(
}
}
static class E
{
internal static void F(this object x, object y) { }
internal static void F<T>(this T t) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GetSpecialType(SpecialType.System_String);
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void string.F<string>()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F(object y)",
"void string.F<string>()");
// Inapplicable and inaccessible extension methods.
sourceCode =
@"class C
{
void M(string s)
{
/*<bind>*/s.F<string>/*</bind>*/(
}
}
static class E
{
internal static void F(this object x, object y) { }
private static void F<T>(this T t) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GetSpecialType(SpecialType.System_String);
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void string.F<string>()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F(object y)");
// Multiple scopes.
sourceCode =
@"namespace N1
{
static class E
{
internal static void F(this object o) { }
}
}
namespace N2
{
using N1;
class C
{
static void M(C c)
{
/*<bind>*/c.F/*</bind>*/(
}
void F(int x) { }
}
static class E
{
internal static void F(this object x, object y) { }
}
}
static class E
{
internal static void F(this object x, object y, object z) { }
}";
compilation = CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N2").GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void object.F(object y)",
"void object.F()",
"void object.F(object y, object z)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void object.F(object y)",
"void object.F()",
"void object.F(object y, object z)");
// Multiple scopes, no instance methods.
sourceCode =
@"namespace N
{
class C
{
static void M(C c)
{
/*<bind>*/c.F/*</bind>*/(
}
}
static class E
{
internal static void F(this object x, object y) { }
}
}
static class E
{
internal static void F(this object x, object y, object z) { }
}";
compilation = CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N").GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void object.F(object y)",
"void object.F(object y, object z)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F(object y)",
"void object.F(object y, object z)");
}
[ClrOnlyFact]
public void PropertyGroup()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Class A
Property P(Optional x As Integer = 0) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Property P(x As Integer, y As Integer) As Integer
Get
Return Nothing
End Get
Set
End Set
End Property
Property P(x As Integer, y As String) As String
Get
Return Nothing
End Get
Set
End Set
End Property
End Class";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped);
// Assignment (property group).
var source2 =
@"class B
{
static void M(A a)
{
/*<bind>*/a.P/*</bind>*/[1, null] = string.Empty;
}
}";
var compilation = CreateCompilation(source2, new[] { reference1 });
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.MemberGroup,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Assignment (property access).
source2 =
@"class B
{
static void M(A a)
{
/*<bind>*/a.P[1, null]/*</bind>*/ = string.Empty;
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.MemberGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Object initializer.
source2 =
@"class B
{
static A F = new A() { /*<bind>*/P/*</bind>*/ = 1 };
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object A.P[int x = 0]");
Utils.CheckISymbols(semanticInfo.MemberGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Incomplete reference, overload resolution failure (property group).
source2 =
@"class B
{
static void M(A a)
{
var o = /*<bind>*/a.P/*</bind>*/[1, a
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MemberGroup,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
// Incomplete reference, overload resolution failure (property access).
source2 =
@"class B
{
static void M(A a)
{
var o = /*<bind>*/a.P[1, a/*</bind>*/
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MemberGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
}
[ClrOnlyFact]
public void PropertyGroupOverloadsOverridesHides()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Class A
Overridable ReadOnly Property P1(index As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P2(index As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P2(x As Object, y As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P3(index As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P3(x As Object, y As Object) As Object
Get
Return Nothing
End Get
End Property
End Class
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E212"")>
Public Class B
Inherits A
Overrides ReadOnly Property P1(index As Object) As Object
Get
Return Nothing
End Get
End Property
Shadows ReadOnly Property P2(index As String) As Object
Get
Return Nothing
End Get
End Property
End Class";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped);
// Overridden property.
var source2 =
@"class C
{
static object F(B b)
{
return /*<bind>*/b.P1/*</bind>*/[null];
}
}";
var compilation = CreateCompilation(source2, new[] { reference1 });
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object B.P1[object index]");
Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P1[object index]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Hidden property.
source2 =
@"class C
{
static object F(B b)
{
return /*<bind>*/b.P2/*</bind>*/[null];
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object B.P2[string index]");
Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P2[string index]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Overloaded property.
source2 =
@"class C
{
static object F(B b)
{
return /*<bind>*/b.P3/*</bind>*/[null];
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object A.P3[object index]");
Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P3[object index]", "object A.P3[object x, object y]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
}
[WorkItem(538859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538859")]
[Fact]
public void ThisExpression()
{
string sourceCode = @"
class C
{
void M()
{
/*<bind>*/this/*</bind>*/.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C this", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538143")]
[Fact]
public void GetSemanticInfoOfNull()
{
var compilation = CreateCompilation("");
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetConstantValue((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ConstructorInitializerSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ConstructorInitializerSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ConstructorInitializerSyntax)null));
}
[WorkItem(537860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537860")]
[Fact]
public void UsingNamespaceName()
{
string sourceCode = @"
using /*<bind>*/System/*</bind>*/;
class Test
{
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3017, "DevDiv_Projects/Roslyn")]
[Fact]
public void VariableUsedInForInit()
{
string sourceCode = @"
class Test
{
void Fill()
{
for (int i = 0; /*<bind>*/i/*</bind>*/ < 10 ; i++ )
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527269")]
[Fact]
public void NullLiteral()
{
string sourceCode = @"
class Test
{
public static void Main()
{
string s = /*<bind>*/null/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[WorkItem(3019, "DevDiv_Projects/Roslyn")]
[Fact]
public void PostfixIncrement()
{
string sourceCode = @"
class Test
{
public static void Main()
{
int i = 10;
/*<bind>*/i++/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 System.Int32.op_Increment(System.Int32 value)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3199, "DevDiv_Projects/Roslyn")]
[Fact]
public void ConditionalOrExpr()
{
string sourceCode = @"
class Program
{
static void T1()
{
bool result = /*<bind>*/true || true/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[WorkItem(3222, "DevDiv_Projects/Roslyn")]
[Fact]
public void ConditionalOperExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
int i = /*<bind>*/(true ? 0 : 1)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(0, semanticInfo.ConstantValue);
}
[WorkItem(3223, "DevDiv_Projects/Roslyn")]
[Fact]
public void DefaultValueExpr()
{
string sourceCode = @"
class Test
{
static void Main(string[] args)
{
int s = /*<bind>*/default(int)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(0, semanticInfo.ConstantValue);
}
[WorkItem(537979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537979")]
[Fact]
public void StringConcatWithInt()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
string str = /*<bind>*/""Count value is: "" + 5/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3226, "DevDiv_Projects/Roslyn")]
[Fact]
public void StringConcatWithIntAndNullableInt()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
string str = /*<bind>*/""Count value is: "" + (int?) 10 + 5/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3234, "DevDiv_Projects/Roslyn")]
[Fact]
public void AsOper()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
object o = null;
string str = /*<bind>*/o as string/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537983")]
[Fact]
public void AddWithUIntAndInt()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
uint ui = 0;
ulong ui2 = /*<bind>*/ui + 5/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.UInt32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.UInt64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.UInt32 System.UInt32.op_Addition(System.UInt32 left, System.UInt32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527314")]
[Fact()]
public void AddExprWithNullableUInt64AndInt32()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
ulong? ui = 0;
ulong? ui2 = /*<bind>*/ui + 5/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.UInt64?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.UInt64?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("ulong.operator +(ulong, ulong)", semanticInfo.Symbol.ToString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3248, "DevDiv_Projects/Roslyn")]
[Fact]
public void NegatedIsExpr()
{
string sourceCode = @"
using System;
public class Test
{
public static void Main()
{
Exception e = new Exception();
bool bl = /*<bind>*/!(e is DivideByZeroException)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Boolean.op_LogicalNot(System.Boolean value)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3249, "DevDiv_Projects/Roslyn")]
[Fact]
public void IsExpr()
{
string sourceCode = @"
using System;
public class Test
{
public static void Main()
{
Exception e = new Exception();
bool bl = /*<bind>*/ (e is DivideByZeroException) /*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527324")]
[Fact]
public void ExceptionCatchVariable()
{
string sourceCode = @"
using System;
public class Test
{
public static void Main()
{
try
{
}
catch (Exception e)
{
bool bl = (/*<bind>*/e/*</bind>*/ is DivideByZeroException) ;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Exception", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Exception", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Exception e", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3478, "DevDiv_Projects/Roslyn")]
[Fact]
public void GenericInvocation()
{
string sourceCode = @"
class Program {
public static void Ref<T>(T array)
{
}
static void Main()
{
/*<bind>*/Ref<object>(null)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void Program.Ref<System.Object>(System.Object array)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538039")]
[Fact]
public void GlobalAliasQualifiedName()
{
string sourceCode = @"
namespace N1
{
interface I1
{
void Method();
}
}
namespace N2
{
class Test : N1.I1
{
void /*<bind>*/global::N1.I1/*</bind>*/.Method()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.I1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("N1.I1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.I1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527363")]
[Fact]
public void ArrayInitializer()
{
string sourceCode = @"
class Test
{
static void Main()
{
int[] arr = new int[] /*<bind>*/{5}/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538041")]
[Fact]
public void AliasQualifiedName()
{
string sourceCode = @"
using NSA = A;
namespace A
{
class Goo {}
}
namespace B
{
class Test
{
class NSA
{
}
static void Main()
{
/*<bind>*/NSA::Goo/*</bind>*/ goo = new NSA::Goo();
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A.Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A.Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A.Goo", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538021")]
[Fact]
public void EnumToStringInvocationExpr()
{
string sourceCode = @"
using System;
enum E { Red, Blue, Green}
public class MainClass
{
public static int Main ()
{
E e = E.Red;
string s = /*<bind>*/e.ToString()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String System.Enum.ToString()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538026")]
[Fact]
public void ExplIfaceMethInvocationExpr()
{
string sourceCode = @"
namespace N1
{
interface I1
{
int Method();
}
}
namespace N2
{
class Test : N1.I1
{
int N1.I1.Method()
{
return 5;
}
static int Main()
{
Test t = new Test();
if (/*<bind>*/((N1.I1)t).Method()/*</bind>*/ != 5)
return 1;
return 0;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 N1.I1.Method()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538027")]
[Fact]
public void InvocExprWithAliasIdentifierNameSameAsType()
{
string sourceCode = @"
using N1 = NGoo;
namespace NGoo
{
class Goo
{
public static void method() { }
}
}
namespace N2
{
class N1 { }
class Test
{
static void Main()
{
/*<bind>*/N1::Goo.method()/*</bind>*/;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void NGoo.Goo.method()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3498, "DevDiv_Projects/Roslyn")]
[Fact]
public void BaseAccessMethodInvocExpr()
{
string sourceCode = @"
using System;
public class BaseClass
{
public virtual void MyMeth()
{
}
}
public class MyClass : BaseClass
{
public override void MyMeth()
{
/*<bind>*/base.MyMeth()/*</bind>*/;
}
public static void Main()
{
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void BaseClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")]
[Fact]
public void OverloadResolutionForVirtualMethods()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
D d = new D();
string s = ""hello""; long l = 1;
/*<bind>*/d.goo(ref s, l, l)/*</bind>*/;
}
}
public class B
{
// Should bind to this method.
public virtual int goo(ref string x, long y, long z)
{
Console.WriteLine(""Base: goo(ref string x, long y, long z)"");
return 0;
}
public virtual void goo(ref string x, params long[] y)
{
Console.WriteLine(""Base: goo(ref string x, params long[] y)"");
}
}
public class D: B
{
// Roslyn erroneously binds to this override.
// Roslyn binds to the correct method above if you comment out this override.
public override void goo(ref string x, params long[] y)
{
Console.WriteLine(""Derived: goo(ref string x, params long[] y)"");
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 B.goo(ref System.String x, System.Int64 y, System.Int64 z)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")]
[Fact]
public void OverloadResolutionForVirtualMethods2()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
D d = new D();
int i = 1;
/*<bind>*/d.goo(i, i)/*</bind>*/;
}
}
public class B
{
public virtual int goo(params int[] x)
{
Console.WriteLine(""""Base: goo(params int[] x)"""");
return 0;
}
public virtual void goo(params object[] x)
{
Console.WriteLine(""""Base: goo(params object[] x)"""");
}
}
public class D: B
{
public override void goo(params object[] x)
{
Console.WriteLine(""""Derived: goo(params object[] x)"""");
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 B.goo(params System.Int32[] x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ThisInStaticMethod()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/this/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("Program", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("Program this", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Constructor1()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/A/*</bind>*/(4);
}
}
class A
{
public A() { }
public A(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Constructor2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new A(4)/*</bind>*/;
}
}
class A
{
public A() { }
public A(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("A..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void FailedOverloadResolution1()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
/*<bind>*/A.f(o)/*</bind>*/;
}
}
class A
{
public void f(int x, int y) { }
public void f(string z) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void FailedOverloadResolution2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
A./*<bind>*/f/*</bind>*/(o);
}
}
class A
{
public void f(int x, int y) { }
public void f(string z) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void A.f(System.String z)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541745")]
[Fact]
public void FailedOverloadResolution3()
{
string sourceCode = @"
class C
{
public int M { get; set; }
}
static class Extensions1
{
public static int M(this C c) { return 0; }
}
static class Extensions2
{
public static int M(this C c) { return 0; }
}
class Goo
{
void M()
{
C c = new C();
/*<bind>*/c.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("System.Int32 C.M()", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.Int32 C.M()", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542833")]
[Fact]
public void FailedOverloadResolution4()
{
string sourceCode = @"
class C
{
public int M;
}
static class Extensions
{
public static int M(this C c, int i) { return 0; }
}
class Goo
{
void M()
{
C c = new C();
/*<bind>*/c.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SucceededOverloadResolution1()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
/*<bind>*/A.f(""hi"")/*</bind>*/;
}
}
class A
{
public static void f(int x, int y) { }
public static int f(string z) { return 3; }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SucceededOverloadResolution2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
A./*<bind>*/f/*</bind>*/(""hi"");
}
}
class A
{
public static void f(int x, int y) { }
public static int f(string z) { return 3; }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 A.f(System.String z)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541878")]
[Fact]
public void TestCandidateReasonForInaccessibleMethod()
{
string sourceCode = @"
class Test
{
class NestedTest
{
static void Method1()
{
}
}
static void Main()
{
/*<bind>*/NestedTest.Method1()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void Test.NestedTest.Method1()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
}
[WorkItem(541879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541879")]
[Fact]
public void InaccessibleTypeInObjectCreationExpression()
{
string sourceCode = @"
class Test
{
class NestedTest
{
class NestedNestedTest
{
}
}
static void Main()
{
var nnt = /*<bind>*/new NestedTest.NestedNestedTest()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Test.NestedTest.NestedNestedTest..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
}
[WorkItem(541883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541883")]
[Fact]
public void InheritedMemberHiding()
{
string sourceCode = @"
public class A
{
public static int m() { return 1; }
}
public class B : A
{
public static int m() { return 5; }
public static void Main1()
{
/*<bind>*/m/*</bind>*/(10);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 B.m()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 B.m()", sortedMethodGroup[0].ToTestDisplayString());
}
[WorkItem(538106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538106")]
[Fact]
public void UsingAliasNameSystemInvocExpr()
{
string sourceCode = @"
using System = MySystem.IO.StreamReader;
namespace N1
{
using NullStreamReader = System::NullStreamReader;
class Test
{
static int Main()
{
NullStreamReader nr = new NullStreamReader();
/*<bind>*/nr.ReadLine()/*</bind>*/;
return 0;
}
}
}
namespace MySystem
{
namespace IO
{
namespace StreamReader
{
public class NullStreamReader
{
public string ReadLine() { return null; }
}
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String MySystem.IO.StreamReader.NullStreamReader.ReadLine()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538109")]
[Fact]
public void InterfaceMethodImplInvocExpr()
{
string sourceCode = @"
interface ISomething
{
string ToString();
}
class A : ISomething
{
string ISomething.ToString()
{
return null;
}
}
class Test
{
static void Main()
{
ISomething isome = new A();
/*<bind>*/isome.ToString()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String ISomething.ToString()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538112")]
[Fact]
public void MemberAccessMethodWithNew()
{
string sourceCode = @"
public class MyBase
{
public void MyMeth()
{
}
}
public class MyClass : MyBase
{
new public void MyMeth()
{
}
public static void Main()
{
MyClass test = new MyClass();
/*<bind>*/test.MyMeth/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void MyClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void MyClass.MyMeth()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527386")]
[Fact]
public void MethodGroupWithStaticInstanceSameName()
{
string sourceCode = @"
class D
{
public static void M2(int x, int y)
{
}
public void M2(int x)
{
}
}
class C
{
public static void Main()
{
D d = new D();
/*<bind>*/d.M2/*</bind>*/(5);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void D.M2(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void D.M2(System.Int32 x)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void D.M2(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538123")]
[Fact]
public void VirtualOverriddenMember()
{
string sourceCode = @"
public class C1
{
public virtual void M1()
{
}
}
public class C2:C1
{
public override void M1()
{
}
}
public class Test
{
static void Main()
{
C2 c2 = new C2();
/*<bind>*/c2.M1/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void C2.M1()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C2.M1()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538125")]
[Fact]
public void AbstractOverriddenMember()
{
string sourceCode = @"
public abstract class AbsClass
{
public abstract void Test();
}
public class TestClass : AbsClass
{
public override void Test() { }
public static void Main()
{
TestClass tc = new TestClass();
/*<bind>*/tc.Test/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void TestClass.Test()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void TestClass.Test()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DiamondInheritanceMember()
{
string sourceCode = @"
public interface IB { void M(); }
public interface IM1 : IB {}
public interface IM2 : IB {}
public interface ID : IM1, IM2 {}
public class Program
{
public static void Main()
{
ID id = null;
/*<bind>*/id.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
// We must ensure that the method is only found once, even though there are two paths to it.
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void IB.M()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void IB.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InconsistentlyHiddenMember()
{
string sourceCode = @"
public interface IB { void M(); }
public interface IL : IB {}
public interface IR : IB { new void M(); }
public interface ID : IR, IL {}
public class Program
{
public static void Main()
{
ID id = null;
/*<bind>*/id.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
// Even though there is a "path" from ID to IB.M via IL on which IB.M is not hidden,
// it is still hidden because *any possible hiding* hides the method.
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void IR.M()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void IR.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538138")]
[Fact]
public void ParenExprWithMethodInvocExpr()
{
string sourceCode = @"
class Test
{
public static int Meth1()
{
return 9;
}
public static void Main()
{
int var1 = /*<bind>*/(Meth1())/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Test.Meth1()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527397")]
[Fact()]
public void ExplicitIdentityCastExpr()
{
string sourceCode = @"
class Test
{
public static void Main()
{
int i = 10;
object j = /*<bind>*/(int)i/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3652, "DevDiv_Projects/Roslyn")]
[WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")]
[WorkItem(543619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543619")]
[Fact()]
public void OutOfBoundsConstCastToByte()
{
string sourceCode = @"
class Test
{
public static void Main()
{
byte j = unchecked(/*<bind>*/(byte)-123/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal((byte)133, semanticInfo.ConstantValue);
}
[WorkItem(538160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538160")]
[Fact]
public void InsideCollectionsNamespace()
{
string sourceCode = @"
using System;
namespace Collections
{
public class Test
{
public static /*<bind>*/void/*</bind>*/ Main()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Void", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538161")]
[Fact]
public void ErrorTypeNameSameAsVariable()
{
string sourceCode = @"
public class A
{
public static void RunTest()
{
/*<bind>*/B/*</bind>*/ B = new B();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotATypeOrNamespace, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("B B", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Local, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537117")]
[WorkItem(537127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537127")]
[Fact]
public void SystemNamespace()
{
string sourceCode = @"
namespace System
{
class A
{
/*<bind>*/System/*</bind>*/.Exception c;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537118")]
[Fact]
public void SystemNamespace2()
{
string sourceCode = @"
namespace N1
{
namespace N2
{
public class A1 { }
}
public class A2
{
/*<bind>*/N1.N2.A1/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.N2.A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.N2.A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.N2.A1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537119")]
[Fact]
public void SystemNamespace3()
{
string sourceCode = @"
class H<T>
{
}
class A
{
}
namespace N1
{
public class A1
{
/*<bind>*/H<A>/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("H<A>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("H<A>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("H<A>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537124")]
[Fact]
public void SystemNamespace4()
{
string sourceCode = @"
using System;
class H<T>
{
}
class H<T1, T2>
{
}
class A
{
}
namespace N1
{
public class A1
{
/*<bind>*/H<H<A>, H<A>>/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("H<H<A>, H<A>>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("H<H<A>, H<A>>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("H<H<A>, H<A>>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537160")]
[Fact]
public void SystemNamespace5()
{
string sourceCode = @"
namespace N1
{
namespace N2
{
public class A2
{
public class A1 { }
/*<bind>*/N1.N2.A2.A1/*</bind>*/ a;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.N2.A2.A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.N2.A2.A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.N2.A2.A1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537161")]
[Fact]
public void SystemNamespace6()
{
string sourceCode = @"
namespace N1
{
class NC1
{
public class A1 { }
}
public class A2
{
/*<bind>*/N1.NC1.A1/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.NC1.A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.NC1.A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.NC1.A1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537340")]
[Fact]
public void LeftOfDottedTypeName()
{
string sourceCode = @"
class Main
{
A./*<bind>*/B/*</bind>*/ x; // this refers to the B within A.
}
class A {
public class B {}
}
class B {}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A.B", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537592")]
[Fact]
public void Parameters()
{
string sourceCode = @"
class C
{
void M(DateTime dt)
{
/*<bind>*/dt/*</bind>*/.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("DateTime", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("DateTime", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("DateTime dt", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
// TODO: This should probably have a candidate symbol!
[WorkItem(527212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527212")]
[Fact]
public void FieldMemberOfConstructedType()
{
string sourceCode = @"
class C<T> {
public T Field;
}
class D {
void M() {
new C<int>./*<bind>*/Field/*</bind>*/.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C<System.Int32>.Field", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("C<System.Int32>.Field", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
// Should bind to "field" with a candidateReason (not a typeornamespace>)
Assert.NotEqual(CandidateReason.None, semanticInfo.CandidateReason);
Assert.NotEqual(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537593")]
[Fact]
public void Constructor()
{
string sourceCode = @"
class C
{
public C() { /*<bind>*/new C()/*</bind>*/.ToString(); }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538046")]
[Fact]
public void TypeNameInTypeThatMatchesNamespace()
{
string sourceCode = @"
namespace T
{
class T
{
void M()
{
/*<bind>*/T/*</bind>*/.T T = new T.T();
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("T.T", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("T.T", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("T.T", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538267")]
[Fact]
public void RHSExpressionInTryParent()
{
string sourceCode = @"
using System;
public class Test
{
static int Main()
{
try
{
object obj = /*<bind>*/null/*</bind>*/;
}
catch {}
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")]
[Fact]
public void GenericArgumentInBase1()
{
string sourceCode = @"
public class X
{
public interface Z { }
}
class A<T>
{
public class X { }
}
class B : A<B.Y./*<bind>*/Z/*</bind>*/>
{
public class Y : X { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("B.Y.Z", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("B.Y.Z", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")]
[Fact]
public void GenericArgumentInBase2()
{
string sourceCode = @"
public class X
{
public interface Z { }
}
class A<T>
{
public class X { }
}
class B : /*<bind>*/A<B.Y.Z>/*</bind>*/
{
public class Y : X { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A<B.Y.Z>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A<B.Y.Z>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A<B.Y.Z>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538097")]
[Fact]
public void InvokedLocal1()
{
string sourceCode = @"
class C
{
static void Goo()
{
int x = 10;
/*<bind>*/x/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538318")]
[Fact]
public void TooManyConstructorArgs()
{
string sourceCode = @"
class C
{
C() {}
void M()
{
/*<bind>*/new C(null
/*</bind>*/ }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538185")]
[Fact]
public void NamespaceAndFieldSameName1()
{
string sourceCode = @"
class C
{
void M()
{
/*<bind>*/System/*</bind>*/.String x = F();
}
string F()
{
return null;
}
public int System;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void PEProperty()
{
string sourceCode = @"
class C
{
void M(string s)
{
/*<bind>*/s.Length/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 System.String.Length { get; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NotPresentGenericType1()
{
string sourceCode = @"
class Class { void Test() { /*<bind>*/List<int>/*</bind>*/ l; } }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NotPresentGenericType2()
{
string sourceCode = @"
class Class {
/*<bind>*/List<int>/*</bind>*/ Test() { return null;}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BadArityConstructorCall()
{
string sourceCode = @"
class C<T1>
{
public void Test()
{
C c = new /*<bind>*/C/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C<T1>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BadArityConstructorCall2()
{
string sourceCode = @"
class C<T1>
{
public void Test()
{
C c = /*<bind>*/new C()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("C<T1>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C<T1>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C<T1>..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C<T1>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void UnresolvedBaseConstructor()
{
string sourceCode = @"
class C : B {
public C(int i) /*<bind>*/: base(i)/*</bind>*/ { }
public C(string j, string k) : base() { }
}
class B {
public B(string a, string b) { }
public B() { }
int i;
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("B..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("B..ctor(System.String a, System.String b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BoundBaseConstructor()
{
string sourceCode = @"
class C : B {
public C(int i) /*<bind>*/: base(""hi"", ""hello"")/*</bind>*/ { }
public C(string j, string k) : base() { }
}
class B
{
public B(string a, string b) { }
public B() { }
int i;
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("B..ctor(System.String a, System.String b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540998")]
[Fact]
public void DeclarationWithinSwitchStatement()
{
string sourceCode =
@"class C
{
static void M(int i)
{
switch (i)
{
case 0:
string name = /*<bind>*/null/*</bind>*/;
if (name != null)
{
}
break;
}
}
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.NotNull(semanticInfo);
}
[WorkItem(537573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537573")]
[Fact]
public void UndeclaredTypeAndCheckContainingSymbol()
{
string sourceCode = @"
class C1
{
void M()
{
/*<bind>*/F/*</bind>*/ f;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("F", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("F", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.Equal(SymbolKind.Namespace, semanticInfo.Type.ContainingSymbol.Kind);
Assert.True(((INamespaceSymbol)semanticInfo.Type.ContainingSymbol).IsGlobalNamespace);
}
[WorkItem(538538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538538")]
[Fact]
public void AliasQualifier()
{
string sourceCode = @"
using X = A;
namespace A.B { }
namespace N
{
using /*<bind>*/X/*</bind>*/::B;
class X { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("X=A", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AliasQualifier2()
{
string sourceCode = @"
using S = System.String;
{
class X
{
void Goo()
{
string x;
x = /*<bind>*/S/*</bind>*/.Empty;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Equal("S=System.String", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal("String", aliasInfo.Target.Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void PropertyAccessor()
{
string sourceCode = @"
class C
{
private object p = null;
internal object P { set { p = /*<bind>*/value/*</bind>*/; } }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Object value", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void IndexerAccessorValue()
{
string sourceCode =
@"class C
{
string[] values = new string[10];
internal string this[int i]
{
get { return values[i]; }
set { values[i] = /*<bind>*/value/*</bind>*/; }
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("System.String value", semanticInfo.Symbol.ToTestDisplayString());
}
[Fact]
public void IndexerAccessorParameter()
{
string sourceCode =
@"class C
{
string[] values = new string[10];
internal string this[short i]
{
get { return values[/*<bind>*/i/*</bind>*/]; }
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("System.Int16 i", semanticInfo.Symbol.ToTestDisplayString());
}
[Fact]
public void IndexerAccessNamedParameter()
{
string sourceCode =
@"class C
{
string[] values = new string[10];
internal string this[short i]
{
get { return values[i]; }
}
void Method()
{
string s = this[/*<bind>*/i/*</bind>*/: 0];
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
var symbol = semanticInfo.Symbol;
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.True(symbol.ContainingSymbol.Kind == SymbolKind.Property && ((IPropertySymbol)symbol.ContainingSymbol).IsIndexer);
Assert.Equal("System.Int16 i", symbol.ToTestDisplayString());
}
[Fact]
public void LocalConstant()
{
string sourceCode = @"
class C
{
static void M()
{
const int i = 1;
const int j = i + 1;
const int k = /*<bind>*/j/*</bind>*/ - 2;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 j", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2, semanticInfo.ConstantValue);
var symbol = (ILocalSymbol)semanticInfo.Symbol;
Assert.True(symbol.HasConstantValue);
Assert.Equal(2, symbol.ConstantValue);
}
[Fact]
public void FieldConstant()
{
string sourceCode = @"
class C
{
const int i = 1;
const int j = i + 1;
static void M()
{
const int k = /*<bind>*/j/*</bind>*/ - 2;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 C.j", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2, semanticInfo.ConstantValue);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.Equal("j", symbol.Name);
Assert.True(symbol.HasConstantValue);
Assert.Equal(2, symbol.ConstantValue);
}
[Fact]
public void FieldInitializer()
{
string sourceCode = @"
class C
{
int F = /*<bind>*/G() + 1/*</bind>*/;
static int G()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void EnumConstant()
{
string sourceCode = @"
enum E { A, B, C, D = B }
class C
{
static void M(E e)
{
M(/*<bind>*/E.C/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2, semanticInfo.ConstantValue);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("C", symbol.Name);
Assert.True(symbol.HasConstantValue);
Assert.Equal(2, symbol.ConstantValue);
}
[Fact]
public void BadEnumConstant()
{
string sourceCode = @"
enum E { W = Z, X, Y }
class C
{
static void M(E e)
{
M(/*<bind>*/E.Y/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.Y", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("Y", symbol.Name);
Assert.False(symbol.HasConstantValue);
}
[Fact]
public void CircularEnumConstant01()
{
string sourceCode = @"
enum E { A = B, B }
class C
{
static void M(E e)
{
M(/*<bind>*/E.B/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("B", symbol.Name);
Assert.False(symbol.HasConstantValue);
}
[Fact]
public void CircularEnumConstant02()
{
string sourceCode = @"
enum E { A = 10, B = C, C, D }
class C
{
static void M(E e)
{
M(/*<bind>*/E.D/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.D", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("D", symbol.Name);
Assert.False(symbol.HasConstantValue);
}
[Fact]
public void EnumInitializer()
{
string sourceCode = @"
enum E { A, B = 3 }
enum F { C, D = 1 + /*<bind>*/E.B/*</bind>*/ }
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(3, semanticInfo.ConstantValue);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("B", symbol.Name);
Assert.True(symbol.HasConstantValue);
Assert.Equal(3, symbol.ConstantValue);
}
[Fact]
public void ParameterOfExplicitInterfaceImplementation()
{
string sourceCode = @"
class Class : System.IFormattable
{
string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider)
{
return /*<bind>*/format/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String format", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BaseConstructorInitializer()
{
string sourceCode = @"
class Class
{
Class(int x) : this(/*<bind>*/x/*</bind>*/ , x) { }
Class(int x, int y) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.ContainingSymbol.Kind);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind);
}
[WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")]
[WorkItem(527831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527831")]
[WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")]
[Fact]
public void InaccessibleMethodGroup()
{
string sourceCode = @"
class C
{
private static void M(long i) { }
private static void M(int i) { }
}
class D
{
void Goo()
{
C./*<bind>*/M/*</bind>*/(1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal("void C.M(System.Int64 i)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void C.M(System.Int64 i)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_Constructors_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = /*<bind>*/new Class1(3, 7)/*</bind>*/;
}
}
class Class1
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleMethodGroup_Constructors_ImplicitObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
Class1 x = /*<bind>*/new(3, 7)/*</bind>*/;
}
}
class Class1
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_Constructors_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = new /*<bind>*/Class1/*</bind>*/(3, 7);
}
}
class Class1
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_AttributeSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1(3, 7)/*</bind>*/]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_Attribute_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1/*</bind>*/(3, 7)]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = /*<bind>*/new Class1(3, 7)/*</bind>*/;
}
}
class Class1
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = new /*<bind>*/Class1/*</bind>*/(3, 7);
}
}
class Class1
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_AttributeSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1(3, 7)/*</bind>*/]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_Attribute_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1/*</bind>*/(3, 7)]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")]
[Fact]
public void SyntaxErrorInReceiver()
{
string sourceCode = @"
public delegate int D(int x);
public class C
{
public C(int i) { }
public void M(D d) { }
}
class Main
{
void Goo(int a)
{
new C(a.).M(x => /*<bind>*/x/*</bind>*/);
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")]
[Fact]
public void SyntaxErrorInReceiverWithExtension()
{
string sourceCode = @"
public delegate int D(int x);
public static class CExtensions
{
public static void M(this C c, D d) { }
}
public class C
{
public C(int i) { }
}
class Main
{
void Goo(int a)
{
new C(a.).M(x => /*<bind>*/x/*</bind>*/);
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")]
[Fact]
public void NonStaticInstanceMismatchMethodGroup()
{
string sourceCode = @"
class C
{
public static int P { get; set; }
}
class D
{
void Goo()
{
C./*<bind>*/set_P/*</bind>*/(1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.P.set", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(MethodKind.PropertySet, ((IMethodSymbol)sortedCandidates[0]).MethodKind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.P.set", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540360")]
[Fact]
public void DuplicateTypeName()
{
string sourceCode = @"
struct C { }
class C
{
public static void M() { }
}
enum C { A, B }
class D
{
static void Main()
{
/*<bind>*/C/*</bind>*/.M();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("C", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal("C", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[2].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void IfCondition()
{
string sourceCode = @"
class C
{
void M(int x)
{
if (/*<bind>*/x == 10/*</bind>*/) {}
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ForCondition()
{
string sourceCode = @"
class C
{
void M(int x)
{
for (int i = 0; /*<bind>*/i < 10/*</bind>*/; i = i + 1) { }
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(539925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539925")]
[Fact]
public void LocalIsFromSource()
{
string sourceCode = @"
class C
{
void M()
{
int x = 1;
int y = /*<bind>*/x/*</bind>*/;
}
}
";
var compilation = CreateCompilation(sourceCode);
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(compilation);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.True(semanticInfo.Symbol.GetSymbol().IsFromCompilation(compilation));
}
[WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")]
[Fact]
public void InEnumElementInitializer()
{
string sourceCode = @"
class C
{
public const int x = 1;
}
enum E
{
q = /*<bind>*/C.x/*</bind>*/,
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")]
[Fact]
public void InEnumOfByteElementInitializer()
{
string sourceCode = @"
class C
{
public const int x = 1;
}
enum E : byte
{
q = /*<bind>*/C.x/*</bind>*/,
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540672")]
[Fact]
public void LambdaExprWithErrorTypeInObjectCreationExpression()
{
var text = @"
class Program
{
static int Main()
{
var d = /*<bind>*/() => { if (true) return new X(); else return new Y(); }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(text);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[Fact]
public void LambdaExpression()
{
string sourceCode = @"
using System;
public class TestClass
{
public static void Main()
{
Func<string, int> f = /*<bind>*/str => 10/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Func<System.String, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol);
Assert.Equal(1, lambdaSym.Parameters.Length);
Assert.Equal("str", lambdaSym.Parameters[0].Name);
Assert.Equal("System.String", lambdaSym.Parameters[0].Type.ToTestDisplayString());
Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString());
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void UnboundLambdaExpression()
{
string sourceCode = @"
using System;
public class TestClass
{
public static void Main()
{
object f = /*<bind>*/str => 10/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol);
Assert.Equal(1, lambdaSym.Parameters.Length);
Assert.Equal("str", lambdaSym.Parameters[0].Name);
Assert.Equal(TypeKind.Error, lambdaSym.Parameters[0].Type.TypeKind);
Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString());
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540650")]
[Fact]
public void TypeOfExpression()
{
string sourceCode = @"
class C
{
static void Main()
{
System.Console.WriteLine(/*<bind>*/typeof(C)/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<TypeOfExpressionSyntax>(sourceCode);
Assert.Equal("System.Type", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_If()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
if (c)
int j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_For()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
for (; c; c = !c)
label: /*<bind>*/c/*</bind>*/ = false;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_While()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
while (c)
int j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_ForEach()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
foreach (string s in args)
label: /*<bind>*/c/*</bind>*/ = false;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_Else()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
if (c);
else
long j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_Do()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
do
label: /*<bind>*/c/*</bind>*/ = false;
while(c);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_Using()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
using(null)
long j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_Lock()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
lock(this)
label: /*<bind>*/c/*</bind>*/ = false;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_Fixed()
{
string sourceCode = @"
unsafe class Program
{
static void Main(string[] args)
{
bool c = true;
fixed (bool* p = &c)
int j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")]
[Fact]
public void BindLiteralCastToDouble()
{
string sourceCode = @"
class MyClass
{
double dbl = /*<bind>*/1/*</bind>*/ ;
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540803")]
[Fact]
public void BindDefaultOfVoidExpr()
{
string sourceCode = @"
class C
{
void M()
{
return /*<bind>*/default(void)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(SpecialType.System_Void, semanticInfo.Type.SpecialType);
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void GetSemanticInfoForBaseConstructorInitializer()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: base()/*</bind>*/ { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void GetSemanticInfoForThisConstructorInitializer()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: this(1)/*</bind>*/ { }
C(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")]
[Fact]
public void ThisStaticConstructorInitializer()
{
string sourceCode = @"
class MyClass
{
static MyClass()
/*<bind>*/: this()/*</bind>*/
{
intI = 2;
}
public MyClass() { }
static int intI = 1;
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("MyClass..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")]
[Fact]
public void IncompleteForEachWithArrayCreationExpr()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
foreach (var f in new int[] { /*<bind>*/5/*</bind>*/
{
Console.WriteLine(f);
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(5, (int)semanticInfo.ConstantValue.Value);
}
[WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")]
[Fact]
public void EmptyStatementInForEach()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
foreach (var a in /*<bind>*/args/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, ((IArrayTypeSymbol)semanticInfo.Type).ElementType.SpecialType);
// CONSIDER: we could conceivable use the foreach collection type (vs the type of the collection expr).
Assert.Equal(SpecialType.System_Collections_IEnumerable, semanticInfo.ConvertedType.SpecialType);
Assert.Equal("args", semanticInfo.Symbol.Name);
}
[WorkItem(540922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540922")]
[WorkItem(541030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541030")]
[Fact]
public void ImplicitlyTypedForEachIterationVariable()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
foreach (/*<bind>*/var/*</bind>*/ a in args);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
var symbol = semanticInfo.Symbol;
Assert.Equal(SymbolKind.NamedType, symbol.Kind);
Assert.Equal(SpecialType.System_String, ((ITypeSymbol)symbol).SpecialType);
}
[Fact]
public void ForEachCollectionConvertedType()
{
// Arrays don't actually use IEnumerable, but that's the spec'd behavior.
CheckForEachCollectionConvertedType("int[]", "System.Int32[]", "System.Collections.IEnumerable");
CheckForEachCollectionConvertedType("int[,]", "System.Int32[,]", "System.Collections.IEnumerable");
// Strings don't actually use string.GetEnumerator, but that's the spec'd behavior.
CheckForEachCollectionConvertedType("string", "System.String", "System.String");
// Special case for dynamic
CheckForEachCollectionConvertedType("dynamic", "dynamic", "System.Collections.IEnumerable");
// Pattern-based, not interface-based
CheckForEachCollectionConvertedType("System.Collections.Generic.List<int>", "System.Collections.Generic.List<System.Int32>", "System.Collections.Generic.List<System.Int32>");
// Interface-based
CheckForEachCollectionConvertedType("Enumerable", "Enumerable", "System.Collections.IEnumerable"); // helper method knows definition of this type
// Interface
CheckForEachCollectionConvertedType("System.Collections.Generic.IEnumerable<int>", "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.Generic.IEnumerable<System.Int32>");
// Interface
CheckForEachCollectionConvertedType("NotAType", "NotAType", "NotAType"); // name not in scope
}
private void CheckForEachCollectionConvertedType(string sourceType, string typeDisplayString, string convertedTypeDisplayString)
{
string template = @"
public class Enumerable : System.Collections.IEnumerable
{{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{{
return null;
}}
}}
class Program
{{
void M({0} collection)
{{
foreach (var v in /*<bind>*/collection/*</bind>*/);
}}
}}
";
var semanticInfo = GetSemanticInfoForTest(string.Format(template, sourceType));
Assert.Equal(typeDisplayString, semanticInfo.Type.ToTestDisplayString());
Assert.Equal(convertedTypeDisplayString, semanticInfo.ConvertedType.ToTestDisplayString());
}
[Fact]
public void InaccessibleParameter()
{
string sourceCode = @"
using System;
class Outer
{
class Inner
{
}
}
class Program
{
public static void f(Outer.Inner a) { /*<bind>*/a/*</bind>*/ = 4; }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Outer.Inner", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Outer.Inner", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Outer.Inner a", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
// Parameter's type is an error type, because Outer.Inner is inaccessible.
var param = (IParameterSymbol)semanticInfo.Symbol;
Assert.Equal(TypeKind.Error, param.Type.TypeKind);
// It's type is not equal to the SemanticInfo type, because that is
// not an error type.
Assert.NotEqual(semanticInfo.Type, param.Type);
}
[Fact]
public void StructConstructor()
{
string sourceCode = @"
struct Struct{
public static void Main()
{
Struct s = /*<bind>*/new Struct()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
var symbol = semanticInfo.Symbol;
Assert.NotNull(symbol);
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)symbol).MethodKind);
Assert.True(symbol.IsImplicitlyDeclared);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void MethodGroupAsArgOfInvalidConstructorCall()
{
string sourceCode = @"
using System;
class Class { string M(int i) { new T(/*<bind>*/M/*</bind>*/); } }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.String Class.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.String Class.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void MethodGroupInReturnStatement()
{
string sourceCode = @"
class C
{
public delegate int Func(int i);
public Func Goo()
{
return /*<bind>*/Goo/*</bind>*/;
}
private int Goo(int i)
{
return i;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("C.Func", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C.Goo(int)", semanticInfo.ImplicitConversion.Method.ToString());
Assert.Equal("System.Int32 C.Goo(System.Int32 i)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C.Func C.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.Int32 C.Goo(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateConversionExtensionMethodNoReceiver()
{
string sourceCode =
@"class C
{
static System.Action<object> F()
{
return /*<bind>*/S.E/*</bind>*/;
}
}
static class S
{
internal static void E(this object o) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.NotNull(semanticInfo);
Assert.Equal("System.Action<System.Object>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("void S.E(this System.Object o)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.ImplicitConversion.IsExtensionMethod);
}
[Fact]
public void DelegateConversionExtensionMethod()
{
string sourceCode =
@"class C
{
static System.Action F(object o)
{
return /*<bind>*/o.E/*</bind>*/;
}
}
static class S
{
internal static void E(this object o) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.NotNull(semanticInfo);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("void System.Object.E()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.IsExtensionMethod);
}
[Fact]
public void InferredVarType()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var x = ""hello"";
/*<bind>*/var/*</bind>*/ y = x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InferredVarTypeWithNamespaceInScope()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
namespace var { }
class Program
{
static void Main(string[] args)
{
var x = ""hello"";
/*<bind>*/var/*</bind>*/ y = x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NonInferredVarType()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
namespace N1
{
class var { }
class Program
{
static void Main(string[] args)
{
/*<bind>*/var/*</bind>*/ x = ""hello"";
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("N1.var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.var", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541207")]
[Fact]
public void UndeclaredVarInThrowExpr()
{
string sourceCode = @"
class Test
{
static void Main()
{
throw /*<bind>*/d1.Get/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo);
}
[Fact]
public void FailedConstructorCall()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C { }
class Program
{
static void Main(string[] args)
{
C c = new /*<bind>*/C/*</bind>*/(17);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void FailedConstructorCall2()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C { }
class Program
{
static void Main(string[] args)
{
C c = /*<bind>*/new C(17)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MemberGroup.Length);
Assert.Equal("C..ctor()", semanticInfo.MemberGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541332")]
[Fact]
public void ImplicitConversionCastExpression()
{
string sourceCode = @"
using System;
enum E { a, b }
class Program
{
static int Main()
{
int ret = /*<bind>*/(int) E.b/*</bind>*/;
return ret - 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToString());
Assert.Equal("int", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541333")]
[Fact]
public void ImplicitConversionAnonymousMethod()
{
string sourceCode = @"
using System;
delegate int D();
class Program
{
static int Main()
{
D d = /*<bind>*/delegate() { return int.MaxValue; }/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<AnonymousMethodExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("D", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
sourceCode = @"
using System;
delegate int D();
class Program
{
static int Main()
{
D d = /*<bind>*/() => { return int.MaxValue; }/*</bind>*/;
return 0;
}
}
";
semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("D", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528476")]
[Fact]
public void BindingInitializerToTargetType()
{
string sourceCode = @"
using System;
class Program
{
static int Main()
{
int[] ret = new int[] /*<bind>*/ { 0, 1, 2 } /*</bind>*/;
return ret[0];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
}
[Fact]
public void BindShortMethodArgument()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void goo(short s)
{
}
static void Main(string[] args)
{
goo(/*<bind>*/123/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(123, semanticInfo.ConstantValue);
}
[WorkItem(541400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541400")]
[Fact]
public void BindingAttributeParameter()
{
string sourceCode = @"
using System;
public class MeAttribute : Attribute
{
public MeAttribute(short p)
{
}
}
[Me(/*<bind>*/123/*</bind>*/)]
public class C
{
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal("int", semanticInfo.Type.ToString());
Assert.Equal("short", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BindAttributeFieldNamedArgumentOnMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute
{
public TestAttribute() { }
public string F;
}
class C1
{
[Test(/*<bind>*/F/*</bind>*/=""method"")]
int f() { return 0; }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String TestAttribute.F", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BindAttributePropertyNamedArgumentOnMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute
{
public TestAttribute() { }
public TestAttribute(int i) { }
public string F;
public double P { get; set; }
}
class C1
{
[Test(/*<bind>*/P/*</bind>*/=3.14)]
int f() { return 0; }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Double TestAttribute.P { get; set; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void TestAttributeNamedArgumentValueOnMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute
{
public TestAttribute() { }
public TestAttribute(int i) { }
public string F;
public double P { get; set; }
}
class C1
{
[Test(P=/*<bind>*/1/*</bind>*/)]
int f() { return 0; }
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540775")]
[Fact]
public void LambdaExprPrecededByAnIncompleteUsingStmt()
{
var code = @"
using System;
class Program
{
static void Main(string[] args)
{
using
Func<int, int> Dele = /*<bind>*/ x => { return x; } /*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(code);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[WorkItem(540785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540785")]
[Fact]
public void NestedLambdaExprPrecededByAnIncompleteNamespaceStmt()
{
var code = @"
using System;
class Program
{
static void Main(string[] args)
{
namespace
Func<int, int> f1 = (x) =>
{
Func<int, int> f2 = /*<bind>*/ (y) => { return y; } /*</bind>*/;
return x;
}
;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(code);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[Fact]
public void DefaultStructConstructor()
{
string sourceCode = @"
using System;
struct Struct{
public static void Main()
{
Struct s = new /*<bind>*/Struct/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Struct", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DefaultStructConstructor2()
{
string sourceCode = @"
using System;
struct Struct{
public static void Main()
{
Struct s = /*<bind>*/new Struct()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Struct..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")]
[Fact]
public void BindAttributeInstanceWithoutAttributeSuffix()
{
string sourceCode = @"
[assembly: /*<bind>*/My/*</bind>*/]
class MyAttribute : System.Attribute { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("MyAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")]
[Fact]
public void BindQualifiedAttributeInstanceWithoutAttributeSuffix()
{
string sourceCode = @"
[assembly: /*<bind>*/N1.My/*</bind>*/]
namespace N1
{
class MyAttribute : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode);
Assert.Equal("N1.MyAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540770")]
[Fact]
public void IncompleteDelegateCastExpression()
{
string sourceCode = @"
delegate void D();
class MyClass
{
public static int Main()
{
D d;
d = /*<bind>*/(D) delegate /*</bind>*/
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("D", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("D", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(7177, "DevDiv_Projects/Roslyn")]
[Fact]
public void IncompleteGenericDelegateDecl()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
/*<bind>*/Func<int, int> ()/*</bind>*/
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541120")]
[Fact]
public void DelegateCreationArguments()
{
string sourceCode = @"
class Program
{
int goo(int i) { return i;}
static void Main(string[] args)
{
var r = /*<bind>*/new System.Func<int, int>((arg)=> { return 1;}, goo)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateCreationArguments2()
{
string sourceCode = @"
class Program
{
int goo(int i) { return i;}
static void Main(string[] args)
{
var r = new /*<bind>*/System.Func<int, int>/*</bind>*/((arg)=> { return 1;}, goo);
}
}
";
var semanticInfo = GetSemanticInfoForTest<TypeSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BaseConstructorInitializer2()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: base()/*</bind>*/ { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol).MethodKind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ThisConstructorInitializer2()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: this(1)/*</bind>*/ { }
C(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")]
[Fact]
public void TypeInParentOnFieldInitializer()
{
string sourceCode = @"
class MyClass
{
double dbl = /*<bind>*/1/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[Fact]
public void ExplicitIdentityConversion()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int y = 12;
long x = /*<bind>*/(int)y/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541588")]
[Fact]
public void ImplicitConversionElementsInArrayInit()
{
string sourceCode = @"
class MyClass
{
long[] l1 = {/*<bind>*/4L/*</bind>*/, 5L };
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int64", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(4L, semanticInfo.ConstantValue);
}
[WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")]
[Fact]
public void ImplicitConversionArrayInitializer_01()
{
string sourceCode = @"
class MyClass
{
int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")]
[Fact]
public void ImplicitConversionArrayInitializer_02()
{
string sourceCode = @"
class MyClass
{
void Test()
{
int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541595")]
[Fact]
public void ImplicitConversionExprReturnedByLambda()
{
string sourceCode = @"
using System;
class MyClass
{
Func<long> f1 = () => /*<bind>*/4/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.ImplicitConversion.IsIdentity);
Assert.True(semanticInfo.ImplicitConversion.IsImplicit);
Assert.True(semanticInfo.ImplicitConversion.IsNumeric);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(4, semanticInfo.ConstantValue);
}
[WorkItem(541040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541040")]
[WorkItem(528551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528551")]
[Fact]
public void InaccessibleNestedType()
{
string sourceCode = @"
using System;
internal class EClass
{
private enum EEK { a, b, c, d };
}
class Test
{
public void M(EClass.EEK e)
{
b = /*<bind>*/ e /*</bind>*/;
}
EClass.EEK b = EClass.EEK.a;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(SymbolKind.NamedType, semanticInfo.Type.Kind);
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter1()
{
string sourceCode = @"
using System;
class Program
{
public void f(int x, int y, int z) { }
public void f(string y, string z) { }
public void goo()
{
f(3, /*<bind>*/z/*</bind>*/: 4, y: 9);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 z", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter2()
{
string sourceCode = @"
using System;
class Program
{
public void f(int x, int y, int z) { }
public void f(string y, string z, int q) { }
public void f(string q, int w, int b) { }
public void goo()
{
f(3, /*<bind>*/z/*</bind>*/: ""goo"", y: 9);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 z", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind);
Assert.Equal("System.String z", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter3()
{
string sourceCode = @"
using System;
class Program
{
public void f(int x, int y, int z) { }
public void f(string y, string z, int q) { }
public void f(string q, int w, int b) { }
public void goo()
{
f(3, z: ""goo"", /*<bind>*/yagga/*</bind>*/: 9);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter4()
{
string sourceCode = @"
using System;
namespace ClassLibrary44
{
[MyAttr(/*<bind>*/x/*</bind>*/:1)]
public class Class1
{
}
public class MyAttr: Attribute
{
public MyAttr(int x)
{}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")]
[Fact]
public void ImplicitReferenceConvExtensionMethodReceiver()
{
string sourceCode =
@"public static class Extend
{
public static string TestExt(this object o1)
{
return o1.ToString();
}
}
class Program
{
static void Main(string[] args)
{
string str1 = ""Test"";
var e1 = /*<bind>*/str1/*</bind>*/.TestExt();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.IsReference);
Assert.Equal("System.String str1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
}
[WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")]
[Fact]
public void ImplicitBoxingConvExtensionMethodReceiver()
{
string sourceCode =
@"struct S { }
static class C
{
static void M(S s)
{
/*<bind>*/s/*</bind>*/.F();
}
static void F(this object o)
{
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("S", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.IsBoxing);
Assert.Equal("S s", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
}
[Fact]
public void AttributeSyntaxBinding()
{
string sourceCode = @"
using System;
[/*<bind>*/MyAttr(1)/*</bind>*/]
public class Class1
{
}
public class MyAttr: Attribute
{
public MyAttr(int x)
{}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
// Should bind to constructor.
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void MemberAccessOnErrorType()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
string x1 = A./*<bind>*/M/*</bind>*/.C.D.E;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void MemberAccessOnErrorType2()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
string x1 = A./*<bind>*/M/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")]
[Fact]
public void DelegateCreation1()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = new /*<bind>*/MyDelegate/*</bind>*/(this.F);
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = new MyDelegate(MD1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateCreation1_2()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = /*<bind>*/new MyDelegate(this.F)/*</bind>*/;
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = new MyDelegate(MD1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")]
[Fact]
public void DelegateCreation2()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = new MyDelegate(this.F);
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = new /*<bind>*/MyDelegate/*</bind>*/(MD1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")]
[Fact]
public void DelegateCreation2_2()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = new MyDelegate(this.F);
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = /*<bind>*/new MyDelegate(MD1)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateSignatureMismatch1()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = new /*<bind>*/Action/*</bind>*/(f);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Action", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateSignatureMismatch2()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = /*<bind>*/new Action(f)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateSignatureMismatch3()
{
// This test and the DelegateSignatureMismatch4 should have identical results, as they are semantically identical
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = new Action(/*<bind>*/f/*</bind>*/);
}
}
";
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Empty(semanticInfo.CandidateSymbols);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
}
[Fact]
public void DelegateSignatureMismatch4()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = /*<bind>*/f/*</bind>*/;
}
}
";
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Empty(semanticInfo.CandidateSymbols);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
}
[WorkItem(541802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541802")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void IncompleteLetClause()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
/*<bind>*/var/*</bind>*/ q2 = from x in nums
let z = x.
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541895")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void QueryErrorBaseKeywordAsSelectExpression()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new int[] { 1 };
/*<bind>*/var/*</bind>*/ query2 = from int b in expr1 select base;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541805")]
[Fact]
public void InToIdentifierQueryContinuation()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select /*<bind>*/w/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541833")]
[Fact]
public void InOptimizedAwaySelectClause()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
where x > 1
select /*<bind>*/x/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[Fact]
public void InFromClause()
{
string sourceCode = @"
using System;
using System.Linq;
class C
{
void M()
{
int rolf = 732;
int roark = -9;
var replicator = from r in new List<int> { 1, 2, 9, rolf, /*<bind>*/roark/*</bind>*/ } select r * 2;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541911")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void QueryErrorGroupJoinFromClause()
{
string sourceCode = @"
class Test
{
static void Main()
{
/*<bind>*/var/*</bind>*/ q =
from Goo i in i
from Goo<int> j in j
group i by i
join Goo
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541920")]
[Fact]
public void SymbolInfoForMissingSelectClauseNode()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string[] strings = { };
var query = from s in strings
let word = s.Split(' ')
from w in w
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var selectClauseNode = tree.FindNodeOrTokenByKind(SyntaxKind.SelectClause).AsNode() as SelectClauseSyntax;
var symbolInfo = semanticModel.GetSymbolInfo(selectClauseNode);
// https://github.com/dotnet/roslyn/issues/38509
// Assert.NotEqual(default, symbolInfo);
Assert.Null(symbolInfo.Symbol);
}
[WorkItem(541940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541940")]
[Fact]
public void IdentifierInSelectNotInContext()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string[] strings = { };
var query = from ch in strings
group ch by ch
into chGroup
where chGroup.Count() >= 2
select /*<bind>*/ x1 /*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
}
[Fact]
public void WhereDefinedInType()
{
var csSource = @"
using System;
class Y
{
public int Where(Func<int, bool> predicate)
{
return 45;
}
}
class P
{
static void Main()
{
var src = new Y();
var query = from x in src
where x > 0
select /*<bind>*/ x /*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(csSource);
Assert.Equal("x", semanticInfo.Symbol.Name);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541830")]
[Fact]
public void AttributeUsageError()
{
string sourceCode = @"
using System;
[/*<bind>*/AttributeUsage/*</bind>*/()]
class MyAtt : Attribute
{}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal("AttributeUsageAttribute", semanticInfo.Type.Name);
}
[WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")]
[Fact]
public void OpenGenericTypeInAttribute()
{
string sourceCode = @"
class Gen<T> {}
[/*<bind>*/Gen<T>/*</bind>*/]
public class Test
{
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")]
[Fact]
public void OpenGenericTypeInAttribute02()
{
string sourceCode = @"
class Goo {}
[/*<bind>*/Goo/*</bind>*/]
public class Test
{
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")]
[Fact]
public void IncompleteEmptyAttributeSyntax01()
{
string sourceCode = @"
public class CSEvent {
[
";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax;
var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Symbol);
Assert.Null(semanticInfo.Type);
}
/// <summary>
/// Same as above but with a token after the incomplete
/// attribute so the attribute is not at the end of file.
/// </summary>
[WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")]
[Fact]
public void IncompleteEmptyAttributeSyntax02()
{
string sourceCode = @"
public class CSEvent {
[
}";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax;
var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Symbol);
Assert.Null(semanticInfo.Type);
}
[WorkItem(541857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541857")]
[Fact]
public void EventWithInitializerInInterface()
{
string sourceCode = @"
public delegate void MyDelegate();
interface test
{
event MyDelegate e = /*<bind>*/new MyDelegate(Test.Main)/*</bind>*/;
}
class Test
{
static void Main() { }
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("MyDelegate", semanticInfo.Type.ToTestDisplayString());
}
[Fact]
public void SwitchExpression_Constant01()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/true/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
[WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")]
public void SwitchExpression_Constant02()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
const string s = null;
switch (/*<bind>*/s/*</bind>*/)
{
case null:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[Fact]
[WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")]
public void SwitchExpression_NotConstant()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (/*<bind>*/s/*</bind>*/)
{
case null:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchExpression_Invalid_Lambda()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/()=>3/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Null(semanticInfo.Type);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchExpression_Invalid_MethodGroup()
{
string sourceCode = @"
using System;
public class Test
{
public static int M() {return 0; }
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/M/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Null(semanticInfo.Type);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchExpression_Invalid_GoverningType()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/2.2/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2.2, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_Null()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
const string s = null;
switch (s)
{
case /*<bind>*/null/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[Fact]
public void SwitchCaseLabelExpression_Constant01()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (true)
{
case /*<bind>*/true/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_Constant02()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
const bool x = true;
switch (true)
{
case /*<bind>*/x/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_NotConstant()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
bool x = true;
switch (true)
{
case /*<bind>*/x/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchCaseLabelExpression_CastExpression()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (ret)
{
case /*<bind>*/(int)'a'/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(97, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_Invalid_Lambda()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (s)
{
case /*<bind>*/()=>3/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
CreateCompilation(sourceCode).VerifyDiagnostics(
// (12,30): error CS1003: Syntax error, ':' expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(12, 30),
// (12,30): error CS1513: } expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(12, 30),
// (12,44): error CS1002: ; expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(12, 44),
// (12,44): error CS1513: } expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(12, 44),
// (12,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(12, 28),
// (12,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type.
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(12, 28)
);
}
[Fact]
public void SwitchCaseLabelExpression_Invalid_LambdaWithSyntaxError()
{
string sourceCode = @"
using System;
public class Test
{
static int M() { return 0;}
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (s)
{
case /*<bind>*/()=>/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
CreateCompilation(sourceCode).VerifyDiagnostics(
// (13,30): error CS1003: Syntax error, ':' expected
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(13, 30),
// (13,30): error CS1513: } expected
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(13, 30),
// (13,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(13, 28),
// (13,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type.
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(13, 28)
);
}
[Fact]
public void SwitchCaseLabelExpression_Invalid_MethodGroup()
{
string sourceCode = @"
using System;
public class Test
{
static int M() { return 0;}
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (s)
{
case /*<bind>*/M/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541932")]
[Fact]
public void IndexingExpression()
{
string sourceCode = @"
class Test
{
static void Main()
{
string str = ""Test"";
char ch = str[/*<bind>*/ 0 /*</bind>*/];
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(0, semanticInfo.ConstantValue);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[Fact]
public void InaccessibleInTypeof()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
class B { }
}
class Program
{
static void Main(string[] args)
{
object o = typeof(/*<bind>*/A.B/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode);
Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A.B", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AttributeWithUnboundGenericType01()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/B<>/*</bind>*/))]
class B<T>
{
public class C
{
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.True((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[Fact]
public void AttributeWithUnboundGenericType02()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/B<>.C/*</bind>*/))]
class B<T>
{
public class C
{
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.True((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[Fact]
public void AttributeWithUnboundGenericType03()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/D/*</bind>*/.C<>))]
class B<T>
{
public class C<U>
{
}
}
class D : B<int>
{
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.False((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[Fact]
public void AttributeWithUnboundGenericType04()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/B<>/*</bind>*/.C<>))]
class B<T>
{
public class C<U>
{
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.Equal("B", type.Name);
Assert.True((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[WorkItem(542430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542430")]
[Fact]
public void UnboundTypeInvariants()
{
var sourceCode =
@"using System;
public class A<T>
{
int x;
public class B<U>
{
int y;
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(typeof(/*<bind>*/A<>.B<>/*</bind>*/));
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = (INamedTypeSymbol)semanticInfo.Type;
Assert.Equal("B", type.Name);
Assert.True(type.IsUnboundGenericType);
Assert.False(type.IsErrorType());
Assert.True(type.TypeArguments[0].IsErrorType());
var constructedFrom = type.ConstructedFrom;
Assert.Equal(constructedFrom, constructedFrom.ConstructedFrom);
Assert.Equal(constructedFrom, constructedFrom.TypeParameters[0].ContainingSymbol);
Assert.Equal(constructedFrom.TypeArguments[0], constructedFrom.TypeParameters[0]);
Assert.Equal(type.ContainingSymbol, constructedFrom.ContainingSymbol);
Assert.Equal(type.TypeParameters[0], constructedFrom.TypeParameters[0]);
Assert.False(constructedFrom.TypeArguments[0].IsErrorType());
Assert.NotEqual(type, constructedFrom);
Assert.False(constructedFrom.IsUnboundGenericType);
var a = type.ContainingType;
Assert.Equal(constructedFrom, a.GetTypeMembers("B").Single());
Assert.NotEqual(type.TypeParameters[0], type.OriginalDefinition.TypeParameters[0]); // alpha renamed
Assert.Null(type.BaseType);
Assert.Empty(type.Interfaces);
Assert.NotNull(constructedFrom.BaseType);
Assert.Empty(type.GetMembers());
Assert.NotEmpty(constructedFrom.GetMembers());
Assert.True(a.IsUnboundGenericType);
Assert.False(a.ConstructedFrom.IsUnboundGenericType);
Assert.Equal(1, a.GetMembers().Length);
}
[WorkItem(528659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528659")]
[Fact]
public void AliasTypeName()
{
string sourceCode = @"
using A = System.String;
class Test
{
static void Main()
{
/*<bind>*/A/*</bind>*/ a = null;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal("A", aliasInfo.Name);
Assert.Equal("A=System.String", aliasInfo.ToTestDisplayString());
}
[WorkItem(542000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542000")]
[Fact]
public void AmbigAttributeBindWithoutAttributeSuffix()
{
string sourceCode = @"
namespace Blue
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Red
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Green
{
using Blue;
using Red;
public class Test
{
[/*<bind>*/Description/*</bind>*/(null)]
static void Main()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528669")]
[Fact]
public void AmbigAttributeBind1()
{
string sourceCode = @"
namespace Blue
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Red
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Green
{
using Blue;
using Red;
public class Test
{
[/*<bind>*/DescriptionAttribute/*</bind>*/(null)]
static void Main()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542205")]
[Fact]
public void IncompleteAttributeSymbolInfo()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/ObsoleteAttribute(x/*</bind>*/
static void Main(string[] args)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")]
[Fact]
public void ConstantFieldInitializerExpression()
{
var sourceCode = @"
using System;
public class Aa
{
const int myLength = /*<bind>*/5/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal(5, semanticInfo.ConstantValue);
}
[WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")]
[Fact]
public void CircularConstantFieldInitializerExpression()
{
var sourceCode = @"
public class C
{
const int x = /*<bind>*/x/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542017")]
[Fact]
public void AmbigAttributeBind2()
{
string sourceCode = @"
using System;
[AttributeUsage(AttributeTargets.All)]
public class X : Attribute
{
}
[AttributeUsage(AttributeTargets.All)]
public class XAttribute : Attribute
{
}
[/*<bind>*/X/*</bind>*/]
class Class1
{
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
}
[WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")]
[Fact]
public void AmbigAttributeBind3()
{
string sourceCode = @"
using System;
[AttributeUsage(AttributeTargets.All)]
public class X : Attribute
{
}
[AttributeUsage(AttributeTargets.All)]
public class XAttribute : Attribute
{
}
[/*<bind>*/X/*</bind>*/]
class Class1
{
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
}
[Fact]
public void AmbigAttributeBind4()
{
string sourceCode = @"
namespace ValidWithSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace ValidWithoutSuffix
{
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_01
{
using ValidWithSuffix;
using ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("ValidWithSuffix.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind5()
{
string sourceCode = @"
namespace ValidWithSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace ValidWithSuffix_And_ValidWithoutSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_02
{
using ValidWithSuffix;
using ValidWithSuffix_And_ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.MethodGroup[0].ToDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind6()
{
string sourceCode = @"
namespace ValidWithoutSuffix
{
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace ValidWithSuffix_And_ValidWithoutSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_03
{
using ValidWithoutSuffix;
using ValidWithSuffix_And_ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.MethodGroup[0].ToDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind7()
{
string sourceCode = @"
namespace ValidWithSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace ValidWithoutSuffix
{
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace ValidWithSuffix_And_ValidWithoutSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_04
{
using ValidWithSuffix;
using ValidWithoutSuffix;
using ValidWithSuffix_And_ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind8()
{
string sourceCode = @"
namespace InvalidWithSuffix
{
public class DescriptionAttribute
{
public DescriptionAttribute(string name) { }
}
}
namespace InvalidWithoutSuffix
{
public class Description
{
public Description(string name) { }
}
}
namespace TestNamespace_05
{
using InvalidWithSuffix;
using InvalidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind9()
{
string sourceCode = @"
namespace InvalidWithoutSuffix
{
public class Description
{
public Description(string name) { }
}
}
namespace InvalidWithSuffix_And_InvalidWithoutSuffix
{
public class DescriptionAttribute
{
public DescriptionAttribute(string name) { }
}
public class Description
{
public Description(string name) { }
}
}
namespace TestNamespace_07
{
using InvalidWithoutSuffix;
using InvalidWithSuffix_And_InvalidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("InvalidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact()]
public void AliasAttributeName()
{
string sourceCode = @"
using A = A1;
class A1 : System.Attribute { }
[/*<bind>*/A/*</bind>*/] class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A1..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A1..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("A=A1", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact()]
public void AliasAttributeName_02_AttributeSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact]
public void AliasAttributeName_02_IdentifierNameSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact]
public void AliasAttributeName_03_AttributeSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact]
public void AliasAttributeName_03_IdentifierNameSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact()]
public void AliasQualifiedAttributeName_01()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[global::/*<bind>*/AttributeClass/*</bind>*/.NonAttributeClass()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()),
"IsAttributeName can be true only for alias name being qualified");
}
[Fact]
public void AliasQualifiedAttributeName_02()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[/*<bind>*/global::AttributeClass/*</bind>*/.NonAttributeClass()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<AliasQualifiedNameSyntax>(sourceCode);
Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()),
"IsAttributeName can be true only for alias name being qualified");
}
[Fact]
public void AliasQualifiedAttributeName_03()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[global::AttributeClass./*<bind>*/NonAttributeClass/*</bind>*/()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AliasQualifiedAttributeName_04()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[/*<bind>*/global::AttributeClass.NonAttributeClass/*</bind>*/()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AliasAttributeName_NonAttributeAlias()
{
string sourceCode = @"
using GooAttribute = C;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AliasAttributeName_NonAttributeAlias_GenericType()
{
string sourceCode = @"
using GooAttribute = Gen<int>;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
class Gen<T> { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Gen<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<System.Int32>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<System.Int32>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AmbigAliasAttributeName()
{
string sourceCode = @"
using A = A1;
using AAttribute = A2;
class A1 : System.Attribute { }
class A2 : System.Attribute { }
[/*<bind>*/A/*</bind>*/] class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A1", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("A2", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AmbigAliasAttributeName_02()
{
string sourceCode = @"
using Goo = System.ObsoleteAttribute;
class GooAttribute : System.Attribute { }
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("System.ObsoleteAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AmbigAliasAttributeName_03()
{
string sourceCode = @"
using Goo = GooAttribute;
class GooAttribute : System.Attribute { }
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("GooAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")]
[Fact]
public void AmbigObjectCreationBind()
{
string sourceCode = @"
using System;
public class X
{
}
public struct X
{
}
class Class1
{
public static void Main()
{
object x = new /*<bind>*/X/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("X", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
}
[WorkItem(542027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542027")]
[Fact()]
public void NonStaticMemberOfOuterTypeAccessedViaNestedType()
{
string sourceCode = @"
class MyClass
{
public int intTest = 1;
class TestClass
{
public void TestMeth()
{
int intI = /*<bind>*/ intTest /*</bind>*/;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass.intTest", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")]
[Fact()]
public void ThisInFieldInitializer()
{
string sourceCode = @"
class MyClass
{
public MyClass self = /*<bind>*/ this /*</bind>*/;
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("MyClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MyClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal(1, sortedCandidates.Length);
Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")]
[Fact()]
public void BaseInFieldInitializer()
{
string sourceCode = @"
class MyClass
{
public object self = /*<bind>*/ base /*</bind>*/ .Id();
object Id() { return this; }
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(SymbolKind.Parameter, semanticInfo.CandidateSymbols[0].Kind);
Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal(1, sortedCandidates.Length);
Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact()]
public void MemberAccessToInaccessibleField()
{
string sourceCode = @"
class MyClass1
{
private static int myInt1 = 12;
}
class MyClass2
{
public int myInt2 = /*<bind>*/MyClass1.myInt1/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass1.myInt1", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528682")]
[Fact]
public void PropertyGetAccessWithPrivateGetter()
{
string sourceCode = @"
public class MyClass
{
public int Property
{
private get { return 0; }
set { }
}
}
public class Test
{
public static void Main(string[] args)
{
MyClass c = new MyClass();
int a = c./*<bind>*/Property/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass.Property { private get; set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")]
[Fact]
public void GetAccessPrivateProperty()
{
string sourceCode = @"
public class Test
{
class Class1
{
private int a { get { return 1; } set { } }
}
class Class2 : Class1
{
public int b() { return /*<bind>*/a/*</bind>*/; }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.Class1.a { get; set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")]
[Fact]
public void GetAccessPrivateField()
{
string sourceCode = @"
public class Test
{
class Class1
{
private int a;
}
class Class2 : Class1
{
public int b() { return /*<bind>*/a/*</bind>*/; }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.Class1.a", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")]
[Fact]
public void GetAccessPrivateEvent()
{
string sourceCode = @"
using System;
public class Test
{
class Class1
{
private event Action a;
}
class Class2 : Class1
{
public Action b() { return /*<bind>*/a/*</bind>*/(); }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("event System.Action Test.Class1.a", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Event, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528684")]
[Fact]
public void PropertySetAccessWithPrivateSetter()
{
string sourceCode = @"
public class MyClass
{
public int Property
{
get { return 0; }
private set { }
}
}
public class Test
{
static void Main()
{
MyClass c = new MyClass();
c./*<bind>*/Property/*</bind>*/ = 10;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass.Property { get; private set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void PropertyIndexerAccessWithPrivateSetter()
{
string sourceCode = @"
public class MyClass
{
public object this[int index]
{
get { return null; }
private set { }
}
}
public class Test
{
static void Main()
{
MyClass c = new MyClass();
/*<bind>*/c[0]/*</bind>*/ = null;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Object MyClass.this[System.Int32 index] { get; private set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542065")]
[Fact]
public void GenericTypeWithNoTypeArgsOnAttribute()
{
string sourceCode = @"
class Gen<T> { }
[/*<bind>*/Gen/*</bind>*/]
public class Test
{
public static int Main()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542125")]
[Fact]
public void MalformedSyntaxSemanticModel_Bug9223()
{
string sourceCode = @"
public delegate int D(int x);
public st C
{
public event D EV;
public C(D d)
{
EV = /*<bind>*/d/*</bind>*/;
}
public int OnEV(int x)
{
return x;
}
}
";
// Don't crash or assert.
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
}
[WorkItem(528746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528746")]
[Fact]
public void ImplicitConversionArrayCreationExprInQuery()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q2 = from x in /*<bind>*/new int[] { 4, 5 }/*</bind>*/
select x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542256")]
[Fact]
public void MalformedConditionalExprInWhereClause()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q1 = from x in new int[] { 4, 5 }
where /*<bind>*/new Program()/*</bind>*/ ?
select x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal("Program..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal("Program", semanticInfo.Type.Name);
}
[WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")]
[Fact]
public void MalformedExpressionInSelectClause()
{
string sourceCode = @"
using System.Linq;
class P
{
static void Main()
{
var src = new int[] { 4, 5 };
var q = from x in src
select /*<bind>*/x/*</bind>*/.";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Symbol);
}
[WorkItem(542344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542344")]
[Fact]
public void LiteralExprInGotoCaseInsideSwitch()
{
string sourceCode = @"
public class Test
{
public static void Main()
{
int ret = 6;
switch (ret)
{
case 0:
goto case /*<bind>*/2/*</bind>*/;
case 2:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
Assert.Equal(2, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ImplicitConvCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
long number = 45;
switch (number)
{
case /*<bind>*/21/*</bind>*/:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ErrorConvCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
double number = 45;
switch (number)
{
case /*<bind>*/21/*</bind>*/:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ImplicitConvGotoCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
long number = 45;
switch (number)
{
case 1:
goto case /*<bind>*/21/*</bind>*/;
case 21:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ErrorConvGotoCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
double number = 45;
switch (number)
{
case 1:
goto case /*<bind>*/21/*</bind>*/;
case 21:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")]
[Fact]
public void AttributeSemanticInfo_OverloadResolutionFailure_01()
{
string sourceCode = @"
[module: /*<bind>*/System.Obsolete(typeof(.<>))/*</bind>*/]
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo);
}
[WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")]
[Fact]
public void AttributeSemanticInfo_OverloadResolutionFailure_02()
{
string sourceCode = @"
[module: System./*<bind>*/Obsolete/*</bind>*/(typeof(.<>))]
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo);
}
private void Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(CompilationUtils.SemanticInfoSummary semanticInfo)
{
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")]
[Fact]
public void ObjectCreationSemanticInfo_OverloadResolutionFailure()
{
string sourceCode = @"
using System;
class Goo
{
public Goo() { }
public Goo(int x) { }
public static void Main()
{
var x = new /*<bind>*/Goo/*</bind>*/(typeof(.<>));
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Goo", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectCreationSemanticInfo_OverloadResolutionFailure_2()
{
string sourceCode = @"
using System;
class Goo
{
public Goo() { }
public Goo(int x) { }
public static void Main()
{
var x = /*<bind>*/new Goo(typeof(Goo))/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Goo..ctor(System.Int32 x)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Goo..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ParameterDefaultValue1()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
void f(long i = 32 + Constants./*<bind>*/k/*</bind>*/, long j = i)
{ }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int16 Constants.k", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal((short)9, semanticInfo.ConstantValue);
}
[Fact]
public void ParameterDefaultValue2()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
void f(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/)
{ }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(12, semanticInfo.ConstantValue);
}
[Fact]
public void ParameterDefaultValueInConstructor()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
Class1(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/)
{ }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(12, semanticInfo.ConstantValue);
}
[Fact]
public void ParameterDefaultValueInIndexer()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
public string this[long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/]
{
get { return """"; }
set { }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(12, semanticInfo.ConstantValue);
}
[WorkItem(542589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542589")]
[Fact]
public void UnrecognizedGenericTypeReference()
{
string sourceCode = "/*<bind>*/C<object, string/*</bind>*/";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = (INamedTypeSymbol)semanticInfo.Type;
Assert.Equal("System.Boolean", type.ToTestDisplayString());
}
[WorkItem(542452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542452")]
[Fact]
public void LambdaInSelectExpressionWithObjectCreation()
{
string sourceCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class Test
{
static void Main() { }
static void Goo(List<int> Scores)
{
var z = from y in Scores select new Action(() => { /*<bind>*/var/*</bind>*/ x = y; });
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DefaultOptionalParamValue()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
const bool v = true;
public void Goo(bool b = /*<bind>*/v == true/*</bind>*/)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Boolean.op_Equality(System.Boolean left, System.Boolean right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
public void DefaultOptionalParamValueWithGenericTypes()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public void Goo<T, U>(T t = /*<bind>*/default(U)/*</bind>*/) where U : class, T
{
}
static void Main(string[] args)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode);
Assert.Equal("U", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind);
Assert.Equal("T", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.TypeParameter, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[WorkItem(542850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542850")]
[Fact]
public void InaccessibleExtensionMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
public static class Extensions
{
private static int Goo(this string z) { return 3; }
}
class Program
{
static void Main(string[] args)
{
args[0]./*<bind>*/Goo/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 System.String.Goo()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 System.String.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542883")]
[Fact]
public void InaccessibleNamedAttrArg()
{
string sourceCode = @"
using System;
public class B : Attribute
{
private int X;
}
[B(/*<bind>*/X/*</bind>*/ = 5)]
public class D { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 B.X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528914")]
[Fact]
public void InvalidIdentifierAsAttrArg()
{
string sourceCode = @"
using System.Runtime.CompilerServices;
public interface Interface1
{
[/*<bind>*/IndexerName(null)/*</bind>*/]
string this[int arg]
{
get;
set;
}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542890")]
[Fact()]
public void GlobalIdentifierName()
{
string sourceCode = @"
class Test
{
static void Main()
{
var t1 = new /*<bind>*/global/*</bind>*/::Test();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.Equal("global", aliasInfo.Name);
Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString());
Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace);
Assert.False(aliasInfo.IsExtern);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact()]
public void GlobalIdentifierName2()
{
string sourceCode = @"
class Test
{
/*<bind>*/global/*</bind>*/::Test f;
static void Main()
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.Equal("global", aliasInfo.Name);
Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString());
Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace);
Assert.False(aliasInfo.IsExtern);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542536")]
[Fact]
public void UndeclaredSymbolInDefaultParameterValue()
{
string sourceCode = @"
class Program
{
const int y = 1;
public void Goo(bool x = (undeclared == /*<bind>*/y/*</bind>*/)) { }
static void Main(string[] args)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Program.y", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(543198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543198")]
[Fact]
public void NamespaceAliasInsideMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
using A = NS1;
namespace NS1
{
class B { }
}
class Program
{
class A
{
}
A::B y = null;
void Main()
{
/*<bind>*/A/*</bind>*/::B.Equals(null, null);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
// Should bind to namespace alias A=NS1, not class Program.A.
Assert.Equal("NS1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_ImplicitArrayCreationSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public static int Main()
{
var a = /*<bind>*/new[] { 1, 2, 3 }/*</bind>*/;
return a[0];
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public static int Main()
{
var a = new[] { 1, 2, 3 };
return /*<bind>*/a/*</bind>*/[0];
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32[] a", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_MultiDim_ImplicitArrayCreationSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][, , ] Goo()
{
var a3 = new[] { /*<bind>*/new [,,] {{{1, 2}}}/*</bind>*/, new [,,] {{{3, 4}}} };
return a3;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[,,]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_MultiDim_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][, , ] Goo()
{
var a3 = new[] { new [,,] {{{3, 4}}}, new [,,] {{{3, 4}}} };
return /*<bind>*/a3/*</bind>*/;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32[][,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[][,,]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32[][,,] a3", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_ImplicitArrayCreationSyntax()
{
string sourceCode = @"
public class C
{
public int[] Goo()
{
char c = 'c';
short s1 = 0;
short s2 = -0;
short s3 = 1;
short s4 = -1;
var array1 = /*<bind>*/new[] { s1, s2, s3, s4, c, '1' }/*</bind>*/; // CS0826
return array1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_IdentifierNameSyntax()
{
string sourceCode = @"
public class C
{
public int[] Goo()
{
char c = 'c';
short s1 = 0;
short s2 = -0;
short s3 = 1;
short s4 = -1;
var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826
return /*<bind>*/array1/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("?[] array1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][,,] Goo()
{
var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, 3, 4 }/*</bind>*/, new[,,] { { { 3, 4 } } } };
return a3;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr_02()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][,,] Goo()
{
var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, x, y }/*</bind>*/, new[,,] { { { 3, 4 } } } };
return a3;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Inside_ErrorImplicitArrayCreation()
{
string sourceCode = @"
public class C
{
public int[] Goo()
{
char c = 'c';
short s1 = 0;
short s2 = -0;
short s3 = 1;
short s4 = -1;
var array1 = new[] { /*<bind>*/new[] { 1, 2 }/*</bind>*/, new[] { s1, s2, s3, s4, c, '1' } }; // CS0826
return array1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(543201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543201")]
public void BindVariableIncompleteForLoop()
{
string sourceCode = @"
class Program
{
static void Main()
{
for (int i = 0; /*<bind>*/i/*</bind>*/
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
}
[Fact, WorkItem(542843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542843")]
public void Bug10245()
{
string sourceCode = @"
class C<T> {
public T Field;
}
class D {
void M() {
new C<int>./*<bind>*/Field/*</bind>*/.ToString();
}
}
";
var tree = Parse(sourceCode);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo.CandidateReason);
Assert.Equal(1, symbolInfo.CandidateSymbols.Length);
Assert.Equal("System.Int32 C<System.Int32>.Field", symbolInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Null(symbolInfo.Symbol);
}
[Fact]
public void StaticClassWithinNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/Stat/*</bind>*/();
}
}
static class Stat { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("Stat", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.CandidateSymbols[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void StaticClassWithinNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new Stat()/*</bind>*/;
}
}
static class Stat { }
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Stat", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("Stat", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543534")]
[Fact]
public void InterfaceWithNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/X/*</bind>*/();
}
}
interface X { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InterfaceWithNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new X()/*</bind>*/;
}
}
interface X { }
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("X", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("X", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void TypeParameterWithNew()
{
string sourceCode = @"
using System;
class Program<T>
{
static void f()
{
object o = new /*<bind>*/T/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("T", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.TypeParameter, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void TypeParameterWithNew2()
{
string sourceCode = @"
using System;
class Program<T>
{
static void f()
{
object o = /*<bind>*/new T()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("T", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("T", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AbstractClassWithNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/X/*</bind>*/();
}
}
abstract class X { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MemberGroup.Length);
}
[Fact]
public void AbstractClassWithNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new X()/*</bind>*/;
}
}
abstract class X { }
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("X", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MemberGroup.Length);
}
[Fact()]
public void DynamicWithNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/dynamic/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("dynamic", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact()]
public void DynamicWithNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new dynamic()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("dynamic", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_01()
{
// There must be exactly one user-defined conversion to a non-nullable integral type,
// and there is.
string sourceCode = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static int Main()
{
Conv C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 1;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitUserDefined, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Conv.implicit operator int(Conv)", semanticInfo.ImplicitConversion.Method.ToString());
Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_02()
{
// The specification requires that the user-defined conversion chosen be one
// which converts to an integral or string type, but *not* a nullable integral type,
// oddly enough. Since the only applicable user-defined conversion here would be the
// lifted conversion from Conv? to int?, the resolution of the conversion fails
// and this program produces an error.
string sourceCode = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static int Main()
{
Conv? C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 1;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Conv?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Conv? C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_01()
{
string sourceCode = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator int? (Conv? C)
{
return null;
}
public static int Main()
{
Conv C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 0;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_02()
{
string sourceCode = @"
struct Conv
{
public static int Main()
{
Conv C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 0;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = /*<bind>*/new MemberInitializerTest() { x = 1, y = 2 }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() /*<bind>*/{ x = 1, y = 2 }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_MemberInitializerAssignment_BinaryExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/x = 1/*</bind>*/, y = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_FieldAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/x/*</bind>*/ = 1, y = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_PropertyAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_TypeParameterBaseFieldAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class Base
{
public Base() { }
public int x;
public int y { get; set; }
public static void Main()
{
MemberInitializerTest<Base>.Goo();
}
}
public class MemberInitializerTest<T> where T : Base, new()
{
public static void Goo()
{
var i = new T() { /*<bind>*/x/*</bind>*/ = 1, y = 2 };
System.Console.WriteLine(i.x);
System.Console.WriteLine(i.y);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Base.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_NestedInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
}
public class Test
{
public readonly MemberInitializerTest m = new MemberInitializerTest();
public static void Main()
{
var i = new Test() { m = /*<bind>*/{ x = 1, y = 2 }/*</bind>*/ };
System.Console.WriteLine(i.m.x);
System.Console.WriteLine(i.m.y);
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_NestedInitializer_PropertyAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
}
public class Test
{
public readonly MemberInitializerTest m = new MemberInitializerTest();
public static void Main()
{
var i = new Test() { m = { x = 1, /*<bind>*/y/*</bind>*/ = 2 } };
System.Console.WriteLine(i.m.x);
System.Console.WriteLine(i.m.y);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InaccessibleMember_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
protected int x;
private int y { get; set; }
internal int z;
}
public class Test
{
public static void Main()
{
var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2, z = 3 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_ReadOnlyPropertyAssign_IdentifierNameSyntax()
{
string sourceCode = @"
public struct MemberInitializerTest
{
public readonly int x;
public int y { get { return 0; } }
}
public struct Test
{
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/y/*</bind>*/ = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MemberInitializerTest.y { get; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_WriteOnlyPropertyAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
}
public class Test
{
public MemberInitializerTest m;
public MemberInitializerTest Prop { set { m = value; } }
public static void Main()
{
var i = new Test() { /*<bind>*/Prop/*</bind>*/ = { x = 1, y = 2 } };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MemberInitializerTest Test.Prop { set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_ErrorInitializerType_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public static void Main()
{
var i = new X() { /*<bind>*/x/*</bind>*/ = 0 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InvalidElementInitializer_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x, y;
public static void Main()
{
var i = new MemberInitializerTest { x = 0, /*<bind>*/y/*</bind>*/++ };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.y", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InvalidElementInitializer_InvocationExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/};
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_01()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() };
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_02()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public static MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() };
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_MethodGroupNamedAssignmentLeft_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/Goo/*</bind>*/ };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_DuplicateMemberInitializer_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public static void Main()
{
var i = new MemberInitializerTest() { x = 1, /*<bind>*/x/*</bind>*/ = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = /*<bind>*/new B { 1, i, { 4L }, { 9 }, 3L }/*</bind>*/;
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("B..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("B..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B /*<bind>*/{ 1, i, { 4L }, { 9 }, 3L }/*</bind>*/;
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ElementInitializer_LiteralExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { /*<bind>*/1/*</bind>*/, i, { 4L }, { 9 }, 3L };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[Fact]
public void CollectionInitializer_ElementInitializer_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { 1, /*<bind>*/i/*</bind>*/, { 4L }, { 9 }, 3L };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ComplexElementInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { 1, i, /*<bind>*/{ 4L }/*</bind>*/, { 9 }, 3L };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ComplexElementInitializer_Empty_InitializerExpressionSyntax()
{
string sourceCode = @"
using System.Collections.Generic;
public class MemberInitializerTest
{
public List<int> y;
public static void Main()
{
i = new MemberInitializerTest { y = { /*<bind>*/{ }/*</bind>*/ } }; // CS1920
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ComplexElementInitializer_AddMethodOverloadResolutionFailure()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { /*<bind>*/{ 1, 2 }/*</bind>*/ };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(float i, int j)
{
list.Add(i);
list.Add(j);
}
public void Add(int i, float j)
{
list.Add(i);
list.Add(j);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_Empty_InitializerExpressionSyntax()
{
string sourceCode = @"
using System.Collections.Generic;
public class MemberInitializerTest
{
public static void Main()
{
var i = new List<int>() /*<bind>*/{ }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_Nested_InitializerExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var coll = new List<B> { new B(0) { list = new List<int>() { 1, 2, 3 } }, new B(1) { list = /*<bind>*/{ 2, 3 }/*</bind>*/ } };
DisplayCollection(coll);
return 0;
}
public static void DisplayCollection(IEnumerable<B> collection)
{
foreach (var i in collection)
{
i.Display();
}
}
}
public class B
{
public List<int> list = new List<int>();
public B() { }
public B(int i) { list.Add(i); }
public void Display()
{
foreach (var i in list)
{
Console.WriteLine(i);
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InitializerTypeNotIEnumerable_InitializerExpressionSyntax()
{
string sourceCode = @"
class MemberInitializerTest
{
public static int Main()
{
B coll = new B /*<bind>*/{ 1 }/*</bind>*/;
return 0;
}
}
class B
{
public B() { }
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InvalidInitializer_PostfixUnaryExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int y;
public static void Main()
{
var i = new MemberInitializerTest { /*<bind>*/y++/*</bind>*/ };
}
}
";
var semanticInfo = GetSemanticInfoForTest<PostfixUnaryExpressionSyntax>(sourceCode);
Assert.Equal("?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InvalidInitializer_BinaryExpressionSyntax()
{
string sourceCode = @"
using System.Collections.Generic;
public class MemberInitializerTest
{
public int x;
static MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
int y = 0;
var i = new List<int> { 1, /*<bind>*/Goo().x = 1/*</bind>*/};
}
}
";
var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SimpleNameWithGenericTypeInAttribute()
{
string sourceCode = @"
class Gen<T> { }
class Gen2<T> : System.Attribute { }
[/*<bind>*/Gen/*</bind>*/]
[Gen2]
public class Test
{
public static int Main()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SimpleNameWithGenericTypeInAttribute_02()
{
string sourceCode = @"
class Gen<T> { }
class Gen2<T> : System.Attribute { }
[Gen]
[/*<bind>*/Gen2/*</bind>*/]
public class Test
{
public static int Main()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Gen2<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen2<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen2<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen2<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_VarKeyword_LocalDeclaration()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
/*<bind>*/var/*</bind>*/ rand = new Random();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_VarKeyword_FieldDeclaration()
{
string sourceCode = @"
class Program
{
/*<bind>*/var/*</bind>*/ x = 1;
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_VarKeyword_MethodReturnType()
{
string sourceCode = @"
class Program
{
/*<bind>*/var/*</bind>*/ Goo() {}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_InterfaceCreation_With_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = new /*<bind>*/InterfaceType/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")]
[Fact]
public void SemanticInfo_InterfaceArrayCreation_With_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = new /*<bind>*/InterfaceType/*</bind>*/[] { };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = /*<bind>*/new InterfaceType()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("CoClassType..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")]
[Fact]
public void SemanticInfo_InterfaceArrayCreation_With_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = /*<bind>*/new InterfaceType[] { }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("InterfaceType[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class GenericCoClassType<T, U> : NonGenericInterfaceType
{
public GenericCoClassType(U x) { Console.WriteLine(x); }
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(GenericCoClassType<int, string>))]
public interface NonGenericInterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = new /*<bind>*/NonGenericInterfaceType/*</bind>*/(""string"");
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("NonGenericInterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class GenericCoClassType<T, U> : NonGenericInterfaceType
{
public GenericCoClassType(U x) { Console.WriteLine(x); }
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(GenericCoClassType<int, string>))]
public interface NonGenericInterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = /*<bind>*/new NonGenericInterfaceType(""string"")/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("NonGenericInterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("NonGenericInterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class Wrapper
{
private class CoClassType : InterfaceType
{
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
public interface InterfaceType
{
}
}
public class MainClass
{
public static int Main()
{
var a = new Wrapper./*<bind>*/InterfaceType/*</bind>*/();
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Wrapper.InterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class Wrapper
{
private class CoClassType : InterfaceType
{
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
public interface InterfaceType
{
}
}
public class MainClass
{
public static int Main()
{
var a = /*<bind>*/new Wrapper.InterfaceType()/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Wrapper.InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("Wrapper.InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Wrapper.CoClassType..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("Wrapper.CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(int))]
public interface InterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = /*<bind>*/new InterfaceType()/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("InterfaceType", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax_2()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(int))]
public interface InterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = new /*<bind>*/InterfaceType/*</bind>*/();
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InterfaceType", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543593")]
[Fact]
public void IncompletePropertyAccessStatement()
{
string sourceCode =
@"class C
{
static void M()
{
var c = new { P = 0 };
/*<bind>*/c.P.Q/*</bind>*/ x;
}
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Symbol);
}
[WorkItem(544449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544449")]
[Fact]
public void IndexerAccessorWithSyntaxErrors()
{
string sourceCode =
@"public abstract int this[int i]
(
{
/*<bind>*/get/*</bind>*/;
set;
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Symbol);
}
[WorkItem(545040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545040")]
[Fact]
public void OmittedArraySizeExpressionSyntax()
{
string sourceCode =
@"
class A
{
public static void Main()
{
var arr = new int[5][
];
}
}
";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.First();
var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedArraySizeExpressionSyntax>().Last();
var model = compilation.GetSemanticModel(tree);
var typeInfo = model.GetTypeInfo(node); // Ensure that this doesn't throw.
Assert.NotEqual(default, typeInfo);
}
[WorkItem(11451, "DevDiv_Projects/Roslyn")]
[Fact]
public void InvalidNewInterface()
{
string sourceCode = @"
using System;
public class Program
{
static void Main(string[] args)
{
var c = new /*<bind>*/IFormattable/*</bind>*/
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.IFormattable", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InvalidNewInterface2()
{
string sourceCode = @"
using System;
public class Program
{
static void Main(string[] args)
{
var c = /*<bind>*/new IFormattable()/*</bind>*/
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.IFormattable", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("System.IFormattable", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("System.IFormattable", semanticInfo.CandidateSymbols.First().ToTestDisplayString());
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(545376, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545376")]
[Fact]
public void AssignExprInExternEvent()
{
string sourceCode = @"
struct Class1
{
public event EventHandler e2;
extern public event EventHandler e1 = /*<bind>*/ e2 = new EventHandler(this, new EventArgs()) = null /*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
}
[Fact, WorkItem(531416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531416")]
public void VarEvent()
{
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(@"
event /*<bind>*/var/*</bind>*/ goo;
");
Assert.True(((ITypeSymbol)semanticInfo.Type).IsErrorType());
}
[WorkItem(546083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546083")]
[Fact]
public void GenericMethodAssignedToDelegateWithDeclErrors()
{
string sourceCode = @"
delegate void D(void t);
class C {
void M<T>(T t) {
}
D d = /*<bind>*/M/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Utils.CheckSymbol(semanticInfo.CandidateSymbols.Single(), "void C.M<T>(T t)");
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Null(semanticInfo.Type);
Utils.CheckSymbol(semanticInfo.ConvertedType, "D");
}
[WorkItem(545992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545992")]
[Fact]
public void TestSemanticInfoForMembersOfCyclicBase()
{
string sourceCode = @"
using System;
using System.Collections;
class B : C
{
}
class C : B
{
static void Main()
{
}
void Goo(int x)
{
/*<bind>*/(this).Goo(1)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void C.Goo(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(610975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610975")]
[Fact]
public void AttributeOnTypeParameterWithSameName()
{
string source = @"
class C<[T(a: 1)]T>
{
}
";
var comp = CreateCompilation(source);
comp.GetParseDiagnostics().Verify(); // Syntactically correct.
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var argumentSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single();
var argumentNameSyntax = argumentSyntax.NameColon.Name;
var info = model.GetSymbolInfo(argumentNameSyntax);
}
private void CommonTestParenthesizedMethodGroup(string sourceCode)
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal("void C.Goo()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
[WorkItem(576966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576966")]
public void TestParenthesizedMethodGroup()
{
string sourceCode = @"
class C
{
void Goo()
{
/*<bind>*/Goo/*</bind>*/();
}
}";
CommonTestParenthesizedMethodGroup(sourceCode);
sourceCode = @"
class C
{
void Goo()
{
((/*<bind>*/Goo/*</bind>*/))();
}
}";
CommonTestParenthesizedMethodGroup(sourceCode);
}
[WorkItem(531549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531549")]
[Fact()]
public void Bug531549()
{
var sourceCode1 = @"
class C1
{
void Goo()
{
int x = 2;
long? z = /*<bind>*/x/*</bind>*/;
}
}";
var sourceCode2 = @"
class C2
{
void Goo()
{
long? y = /*<bind>*/x/*</bind>*/;
int x = 2;
}
}";
var compilation = CreateCompilation(new[] { sourceCode1, sourceCode2 });
for (int i = 0; i < 2; i++)
{
var tree = compilation.SyntaxTrees[i];
var model = compilation.GetSemanticModel(tree);
IdentifierNameSyntax syntaxToBind = GetSyntaxNodeOfTypeForBinding<IdentifierNameSyntax>(GetSyntaxNodeList(tree));
var info1 = model.GetTypeInfo(syntaxToBind);
Assert.NotEqual(default, info1);
Assert.Equal("System.Int32", info1.Type.ToTestDisplayString());
}
}
[Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")]
public void ObjectCreation1()
{
var compilation = CreateCompilation(
@"
using System.Collections;
namespace Test
{
class C : IEnumerable
{
public int P1 { get; set; }
public void Add(int x)
{ }
public static void Main()
{
var x1 = new C();
var x2 = new C() {P1 = 1};
var x3 = new C() {1, 2};
}
public static void Main2()
{
var x1 = new Test.C();
var x2 = new Test.C() {P1 = 1};
var x3 = new Test.C() {1, 2};
}
public IEnumerator GetEnumerator()
{
return null;
}
}
}");
compilation.VerifyDiagnostics();
SyntaxTree tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as ObjectCreationExpressionSyntax)).
Where(node => (object)node != null).ToArray();
for (int i = 0; i < 6; i++)
{
ObjectCreationExpressionSyntax creation = nodes[i];
SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type);
Assert.Equal("Test.C", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var memberGroup = model.GetMemberGroup(creation.Type);
Assert.Equal(0, memberGroup.Length);
TypeInfo typeInfo = model.GetTypeInfo(creation.Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
var conv = model.GetConversion(creation.Type);
Assert.True(conv.IsIdentity);
symbolInfo = model.GetSymbolInfo(creation);
Assert.Equal("Test.C..ctor()", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
memberGroup = model.GetMemberGroup(creation);
Assert.Equal(1, memberGroup.Length);
Assert.Equal("Test.C..ctor()", memberGroup[0].ToTestDisplayString());
typeInfo = model.GetTypeInfo(creation);
Assert.Equal("Test.C", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Test.C", typeInfo.ConvertedType.ToTestDisplayString());
conv = model.GetConversion(creation);
Assert.True(conv.IsIdentity);
}
}
[Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")]
public void ObjectCreation2()
{
var compilation = CreateCompilation(
@"
using System.Collections;
namespace Test
{
public class CoClassI : I
{
public int P1 { get; set; }
public void Add(int x)
{ }
public IEnumerator GetEnumerator()
{
return null;
}
}
[System.Runtime.InteropServices.ComImport, System.Runtime.InteropServices.CoClass(typeof(CoClassI))]
[System.Runtime.InteropServices.Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public interface I : IEnumerable
{
int P1 { get; set; }
void Add(int x);
}
class C
{
public static void Main()
{
var x1 = new I();
var x2 = new I() {P1 = 1};
var x3 = new I() {1, 2};
}
public static void Main2()
{
var x1 = new Test.I();
var x2 = new Test.I() {P1 = 1};
var x3 = new Test.I() {1, 2};
}
}
}
");
compilation.VerifyDiagnostics();
SyntaxTree tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as ObjectCreationExpressionSyntax)).
Where(node => (object)node != null).ToArray();
for (int i = 0; i < 6; i++)
{
ObjectCreationExpressionSyntax creation = nodes[i];
SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type);
Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var memberGroup = model.GetMemberGroup(creation.Type);
Assert.Equal(0, memberGroup.Length);
TypeInfo typeInfo = model.GetTypeInfo(creation.Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
var conv = model.GetConversion(creation.Type);
Assert.True(conv.IsIdentity);
symbolInfo = model.GetSymbolInfo(creation);
Assert.Equal("Test.CoClassI..ctor()", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
memberGroup = model.GetMemberGroup(creation);
Assert.Equal(1, memberGroup.Length);
Assert.Equal("Test.CoClassI..ctor()", memberGroup[0].ToTestDisplayString());
typeInfo = model.GetTypeInfo(creation);
Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString());
conv = model.GetConversion(creation);
Assert.True(conv.IsIdentity);
}
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")]
public void ObjectCreation3()
{
var pia = CreateCompilation(
@"
using System;
using System.Collections;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
namespace Test
{
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b5827A"")]
public class CoClassI : I
{
public int P1 { get; set; }
public void Add(int x)
{ }
public IEnumerator GetEnumerator()
{
return null;
}
}
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
[System.Runtime.InteropServices.CoClass(typeof(CoClassI))]
public interface I : IEnumerable
{
int P1 { get; set; }
void Add(int x);
}
}
", options: TestOptions.ReleaseDll);
pia.VerifyDiagnostics();
var compilation = CreateCompilation(
@"
namespace Test
{
class C
{
public static void Main()
{
var x1 = new I();
var x2 = new I() {P1 = 1};
var x3 = new I() {1, 2};
}
public static void Main2()
{
var x1 = new Test.I();
var x2 = new Test.I() {P1 = 1};
var x3 = new Test.I() {1, 2};
}
}
}", references: new[] { new CSharpCompilationReference(pia, embedInteropTypes: true) });
compilation.VerifyDiagnostics();
SyntaxTree tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as ObjectCreationExpressionSyntax)).
Where(node => (object)node != null).ToArray();
for (int i = 0; i < 6; i++)
{
ObjectCreationExpressionSyntax creation = nodes[i];
SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type);
Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var memberGroup = model.GetMemberGroup(creation.Type);
Assert.Equal(0, memberGroup.Length);
TypeInfo typeInfo = model.GetTypeInfo(creation.Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
var conv = model.GetConversion(creation.Type);
Assert.True(conv.IsIdentity);
symbolInfo = model.GetSymbolInfo(creation);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
memberGroup = model.GetMemberGroup(creation);
Assert.Equal(0, memberGroup.Length);
typeInfo = model.GetTypeInfo(creation);
Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString());
conv = model.GetConversion(creation);
Assert.True(conv.IsIdentity);
}
}
/// <summary>
/// SymbolInfo and TypeInfo should implement IEquatable<T>.
/// </summary>
[WorkItem(792647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792647")]
[Fact]
public void ImplementsIEquatable()
{
string sourceCode =
@"class C
{
object F()
{
return this;
}
}";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.First();
var expr = (ExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ThisKeyword).Parent;
var model = compilation.GetSemanticModel(tree);
var symbolInfo1 = model.GetSymbolInfo(expr);
var symbolInfo2 = model.GetSymbolInfo(expr);
var symbolComparer = (IEquatable<SymbolInfo>)symbolInfo1;
Assert.True(symbolComparer.Equals(symbolInfo2));
var typeInfo1 = model.GetTypeInfo(expr);
var typeInfo2 = model.GetTypeInfo(expr);
var typeComparer = (IEquatable<TypeInfo>)typeInfo1;
Assert.True(typeComparer.Equals(typeInfo2));
}
[Fact]
public void ConditionalAccessErr001()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = """"qqq"""" ?/*<bind>*/.ToString().Length/*</bind>*/.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccessErr002()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = ""qqq"" ?/*<bind>*/.ToString/*</bind>*/.Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberBindingExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("string.ToString()", sortedCandidates[0].ToDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("string.ToString(System.IFormatProvider)", sortedCandidates[1].ToDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("string.ToString()", sortedMethodGroup[0].ToDisplayString());
Assert.Equal("string.ToString(System.IFormatProvider)", sortedMethodGroup[1].ToDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess001()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = ""qqq"" ?/*<bind>*/.ToString()/*</bind>*/.Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("string", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("string", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.ToString()", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess002()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = ""qqq"" ?.ToString()./*<bind>*/Length/*</bind>*/.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess003()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString()./*<bind>*/Length/*</bind>*/?.ToString();
var dummy2 = ""qqq""?.ToString().Length.ToString();
var dummy3 = 1.ToString()?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess004()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString()./*<bind>*/Length/*</bind>*/ .ToString();
var dummy2 = ""qqq"" ?.ToString().Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess005()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString() ?/*<bind>*/[1]/*</bind>*/ .ToString();
var dummy2 = ""qqq"" ?.ToString().Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<ElementBindingExpressionSyntax>(sourceCode);
Assert.Equal("char", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("char", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.this[int]", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(998050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998050")]
public void Bug998050()
{
var comp = CreateCompilation(@"
class BaselineLog
{}
public static BaselineLog Log
{
get
{
}
}= new /*<bind>*/BaselineLog/*</bind>*/();
", parseOptions: TestOptions.Regular);
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(comp);
Assert.Null(semanticInfo.Type);
Assert.Equal("BaselineLog", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(982479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/982479")]
public void Bug982479()
{
const string sourceCode = @"
class C
{
static void Main()
{
new C { Dynamic = { /*<bind>*/Name/*</bind>*/ = 1 } };
}
public dynamic Dynamic;
}
class Name
{
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("dynamic", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind);
Assert.Equal("dynamic", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Dynamic, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(1084693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084693")]
public void Bug1084693()
{
const string sourceCode =
@"
using System;
public class C {
public Func<Func<C, C>, C> Select;
public Func<Func<C, bool>, C> Where => null;
public void M() {
var e =
from i in this
where true
select true?i:i;
}
}";
var compilation = CreateCompilation(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
string[] expectedNames = { null, "Where", "Select" };
int i = 0;
foreach (var qc in tree.GetRoot().DescendantNodes().OfType<QueryClauseSyntax>())
{
var infoSymbol = semanticModel.GetQueryClauseInfo(qc).OperationInfo.Symbol;
Assert.Equal(expectedNames[i++], infoSymbol?.Name);
}
var qe = tree.GetRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Single();
var infoSymbol2 = semanticModel.GetSymbolInfo(qe.Body.SelectOrGroup).Symbol;
Assert.Equal(expectedNames[i++], infoSymbol2.Name);
}
[Fact]
public void TestIncompleteMember()
{
// Note: binding information in an incomplete member is not available.
// When https://github.com/dotnet/roslyn/issues/7536 is fixed this test
// will have to be updated.
string sourceCode = @"
using System;
class Program
{
public /*<bind>*/K/*</bind>*/
}
class K
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("K", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(18763, "https://github.com/dotnet/roslyn/issues/18763")]
[Fact]
public void AttributeArgumentLambdaThis()
{
string source =
@"class C
{
[X(() => this._Y)]
public void Z()
{
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.ThisExpression);
var info = model.GetSemanticInfoSummary(syntax);
Assert.Equal("C", info.Type.Name);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
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.Test.Utilities;
using Xunit;
// Note: the easiest way to create new unit tests that use GetSemanticInfo
// is to use the SemanticInfo unit test generate in Editor Test App.
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
using Utils = CompilationUtils;
public class SemanticModelGetSemanticInfoTests : SemanticModelTestBase
{
[Fact]
public void FailedOverloadResolution()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
int i = 8;
int j = i + q;
/*<bind>*/X.f/*</bind>*/(""hello"");
}
}
class X
{
public static void f() { }
public static void f(int i) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void X.f()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("void X.f(System.Int32 i)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void X.f()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void X.f(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SimpleGenericType()
{
string sourceCode = @"
using System;
class Program
{
/*<bind>*/K<int>/*</bind>*/ f;
}
class K<T>
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("K<System.Int32>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity1()
{
string sourceCode = @"
using System;
class Program
{
/*<bind>*/K<int, string>/*</bind>*/ f;
}
class K<T>
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity2()
{
string sourceCode = @"
using System;
class Program
{
/*<bind>*/K/*</bind>*/ f;
}
class K<T>
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity3()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
/*<bind>*/K<int, int>/*</bind>*/.f();
}
}
class K<T>
{
void f() { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void WrongArity4()
{
string sourceCode = @"
using System;
class Program
{
static K Main()
{
/*<bind>*/K/*</bind>*/.f();
}
}
class K<T>
{
void f() { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NotInvocable()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
K./*<bind>*/f/*</bind>*/();
}
}
class K
{
public int f;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotInvocable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleField()
{
string sourceCode = @"
class Program
{
static void Main()
{
K./*<bind>*/f/*</bind>*/ = 3;
}
}
class K
{
private int f;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleFieldAssignment()
{
string sourceCode =
@"class A
{
string F;
}
class B
{
static void M(A a)
{
/*<bind>*/a.F/*</bind>*/ = string.Empty;
}
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
var symbol = semanticInfo.Symbol;
Assert.Null(symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("System.String A.F", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, symbol.Kind);
}
[WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")]
[Fact]
public void InaccessibleBaseClassConstructor01()
{
string sourceCode = @"
namespace Test
{
public class Base
{
protected Base() { }
}
public class Derived : Base
{
void M()
{
Base b = /*<bind>*/new Base()/*</bind>*/;
}
}
}";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Test.Base..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
}
[WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")]
[Fact]
public void InaccessibleBaseClassConstructor02()
{
string sourceCode = @"
namespace Test
{
public class Base
{
protected Base() { }
}
public class Derived : Base
{
void M()
{
Base b = new /*<bind>*/Base/*</bind>*/();
}
}
}";
var semanticInfo = GetSemanticInfoForTest<NameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal("Test.Base", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MemberGroup.Length);
}
[Fact]
public void InaccessibleFieldMethodArg()
{
string sourceCode =
@"class A
{
string F;
}
class B
{
static void M(A a)
{
M(/*<bind>*/a.F/*</bind>*/);
}
static void M(string s) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
var symbol = semanticInfo.Symbol;
Assert.Null(symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("System.String A.F", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, symbol.Kind);
}
[Fact]
public void TypeNotAVariable()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
/*<bind>*/K/*</bind>*/ = 12;
}
}
class K
{
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleType1()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
/*<bind>*/K.J/*</bind>*/ = v;
}
}
class K
{
protected class J { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("K.J", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguousTypesBetweenUsings1()
{
string sourceCode = @"
using System;
using N1;
using N2;
class Program
{
/*<bind>*/A/*</bind>*/ field;
}
namespace N1
{
class A { }
}
namespace N2
{
class A { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguousTypesBetweenUsings2()
{
string sourceCode = @"
using System;
using N1;
using N2;
class Program
{
void f()
{
/*<bind>*/A/*</bind>*/.g();
}
}
namespace N1
{
class A { }
}
namespace N2
{
class A { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguousTypesBetweenUsings3()
{
string sourceCode = @"
using System;
using N1;
using N2;
class Program
{
void f()
{
/*<bind>*/A<int>/*</bind>*/.g();
}
}
namespace N1
{
class A<T> { }
}
namespace N2
{
class A<U> { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.A<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("N1.A<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.A<T>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("N2.A<U>", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbiguityBetweenInterfaceMembers()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
interface I1
{
public int P { get; }
}
interface I2
{
public string P { get; }
}
interface I3 : I1, I2
{ }
public class Class1
{
void f()
{
I3 x = null;
int o = x./*<bind>*/P/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("I1.P", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 I1.P { get; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal("System.String I2.P { get; }", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Alias1()
{
string sourceCode = @"
using O = System.Object;
partial class A : /*<bind>*/O/*</bind>*/ {}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Alias2()
{
string sourceCode = @"
using O = System.Object;
partial class A {
void f()
{
/*<bind>*/O/*</bind>*/.ReferenceEquals(null, null);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(539002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539002")]
[Fact]
public void IncompleteGenericMethodCall()
{
string sourceCode = @"
class Array
{
public static void Find<T>(T t) { }
}
class C
{
static void Main()
{
/*<bind>*/Array.Find<int>/*</bind>*/(
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void IncompleteExtensionMethodCall()
{
string sourceCode =
@"interface I<T> { }
class A { }
class B : A { }
class C
{
static void M(A a)
{
/*<bind>*/a.M/*</bind>*/(
}
}
static class S
{
internal static void M(this object o, int x) { }
internal static void M(this A a, int x, int y) { }
internal static void M(this B b) { }
internal static void M(this string s) { }
internal static void M<T>(this T t, object o) { }
internal static void M<T>(this T[] t) { }
internal static void M<T, U>(this T x, I<T> y, U z) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void object.M(int x)",
"void A.M(int x, int y)",
"void A.M<A>(object o)",
"void A.M<A, U>(I<A> y, U z)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void object.M(int x)",
"void A.M(int x, int y)",
"void A.M<A>(object o)",
"void A.M<A, U>(I<A> y, U z)");
Utils.CheckReducedExtensionMethod(semanticInfo.MethodGroup[3].GetSymbol(),
"void A.M<A, U>(I<A> y, U z)",
"void S.M<T, U>(T x, I<T> y, U z)",
"void T.M<T, U>(I<T> y, U z)",
"void S.M<T, U>(T x, I<T> y, U z)");
}
[Fact]
public void IncompleteExtensionMethodCallBadThisType()
{
string sourceCode =
@"interface I<T> { }
class B
{
static void M(I<A> a)
{
/*<bind>*/a.M/*</bind>*/(
}
}
static class S
{
internal static void M(this object o) { }
internal static void M<T>(this T t, object o) { }
internal static void M<T>(this T[] t) { }
internal static void M<T, U>(this I<T> x, I<T> y, U z) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void object.M()",
"void I<A>.M<I<A>>(object o)",
"void I<A>.M<A, U>(I<A> y, U z)");
}
[WorkItem(541141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541141")]
[Fact]
public void IncompleteGenericExtensionMethodCall()
{
string sourceCode =
@"using System.Linq;
class C
{
static void M(double[] a)
{
/*<bind>*/a.Where/*</bind>*/(
}
}";
var compilation = CreateCompilation(source: sourceCode);
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, bool> predicate)",
"IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, int, bool> predicate)");
}
[WorkItem(541349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541349")]
[Fact]
public void GenericExtensionMethodCallExplicitTypeArgs()
{
string sourceCode =
@"interface I<T> { }
class C
{
static void M(object o)
{
/*<bind>*/o.E<int>/*</bind>*/();
}
}
static class S
{
internal static void E(this object x, object y) { }
internal static void E<T>(this object o) { }
internal static void E<T>(this object o, T t) { }
internal static void E<T>(this I<T> t) { }
internal static void E<T, U>(this I<T> t) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Utils.CheckSymbol(semanticInfo.Symbol,
"void object.E<int>()");
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void object.E<int>()",
"void object.E<int>(int t)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
}
[Fact]
public void GenericExtensionMethodCallExplicitTypeArgsOfT()
{
string sourceCode =
@"interface I<T> { }
class C
{
static void M<T, U>(T t, U u)
{
/*<bind>*/t.E<T, U>/*</bind>*/(u);
}
}
static class S
{
internal static void E(this object x, object y) { }
internal static void E<T>(this object o) { }
internal static void E<T, U>(this T t, U u) { }
internal static void E<T, U>(this I<T> t, U u) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void T.E<T, U>(U u)");
}
[WorkItem(541297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541297")]
[Fact]
public void GenericExtensionMethodCall()
{
// Single applicable overload with valid argument.
var semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
/*<bind>*/s.E(s)/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, object y) { }
internal static void E<T, U>(this T x, U y) { }
}");
Utils.CheckSymbol(semanticInfo.Symbol,
"void string.E<string, string>(string y)");
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Multiple applicable overloads with valid arguments.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s, object o)
{
/*<bind>*/s.E(s, o)/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this object x, T y, object z) { }
internal static void E<T, U>(this T x, object y, U z) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void object.E<string>(string y, object z)",
"void string.E<string, object>(object y, object z)");
// Multiple applicable overloads with error argument.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
/*<bind>*/s.E(t, s)/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, T y, object z) { }
internal static void E<T, U>(this T x, string y, U z) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void string.E<string>(string y, object z)",
"void string.E<string, string>(string y, string z)");
// Multiple overloads but all inaccessible.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
/*<bind>*/s.E()/*</bind>*/;
}
}
static class S
{
static void E(this string x) { }
static void E<T>(this T x) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols
/* no candidates */
);
}
[Fact]
public void GenericExtensionDelegateMethod()
{
// Single applicable overload.
var semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
System.Action<string> a = /*<bind>*/s.E/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, T y) { }
internal static void E<T>(this object x, T y) { }
}");
Utils.CheckSymbol(semanticInfo.Symbol,
"void string.E<string>(string y)");
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void string.E<string>(string y)",
"void object.E<T>(T y)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Multiple applicable overloads.
semanticInfo = GetSemanticInfoForTest(
@"class C
{
static void M(string s)
{
System.Action<string> a = /*<bind>*/s.E/*</bind>*/;
}
}
static class S
{
internal static void E<T>(this T x, T y) { }
internal static void E<T, U>(this T x, U y) { }
}");
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MethodGroup,
"void string.E<string>(string y)",
"void string.E<string, U>(U y)");
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"void string.E<string>(string y)",
"void string.E<string, U>(U y)");
}
/// <summary>
/// Overloads from different scopes should
/// be included in method group.
/// </summary>
[WorkItem(541890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541890")]
[Fact]
public void IncompleteExtensionOverloadedDifferentScopes()
{
// Instance methods and extension method (implicit instance).
var sourceCode =
@"class C
{
void M()
{
/*<bind>*/F/*</bind>*/(
}
void F(int x) { }
void F(object x, object y) { }
}
static class E
{
internal static void F(this object x, object y) { }
}";
var compilation = (Compilation)CreateCompilation(source: sourceCode);
var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
var symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)");
symbols = model.LookupSymbols(expr.SpanStart, container: null, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)",
"void object.F(object y)");
// Instance methods and extension method (explicit instance).
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F/*</bind>*/(
}
void F(int x) { }
void F(object x, object y) { }
}
static class E
{
internal static void F(this object x, object y) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)",
"void object.F(object y)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void C.F(object x, object y)",
"void object.F(object y)");
// Applicable instance method and inapplicable extension method.
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F<string>/*</bind>*/(
}
void F<T>(T t) { }
}
static class E
{
internal static void F(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F<string>(string t)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F<T>(T t)",
"void object.F()");
// Inaccessible instance method and accessible extension method.
sourceCode =
@"class A
{
void F() { }
}
class B : A
{
static void M(A a)
{
/*<bind>*/a.F/*</bind>*/(
}
}
static class E
{
internal static void F(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void object.F()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F()");
// Inapplicable instance method and applicable extension method.
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F<string>/*</bind>*/(
}
void F(object o) { }
}
static class E
{
internal static void F<T>(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void object.F<string>()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(object o)",
"void object.F<T>()");
// Viable instance and extension methods, binding to extension method.
sourceCode =
@"class C
{
void M()
{
/*<bind>*/this.F/*</bind>*/();
}
void F(object o) { }
}
static class E
{
internal static void F(this object x) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(object o)",
"void object.F()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(object o)",
"void object.F()");
// Applicable and inaccessible extension methods.
sourceCode =
@"class C
{
void M(string s)
{
/*<bind>*/s.F<string>/*</bind>*/(
}
}
static class E
{
internal static void F(this object x, object y) { }
internal static void F<T>(this T t) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GetSpecialType(SpecialType.System_String);
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void string.F<string>()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F(object y)",
"void string.F<string>()");
// Inapplicable and inaccessible extension methods.
sourceCode =
@"class C
{
void M(string s)
{
/*<bind>*/s.F<string>/*</bind>*/(
}
}
static class E
{
internal static void F(this object x, object y) { }
private static void F<T>(this T t) { }
}";
compilation = (Compilation)CreateCompilation(source: sourceCode);
type = compilation.GetSpecialType(SpecialType.System_String);
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void string.F<string>()");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F(object y)");
// Multiple scopes.
sourceCode =
@"namespace N1
{
static class E
{
internal static void F(this object o) { }
}
}
namespace N2
{
using N1;
class C
{
static void M(C c)
{
/*<bind>*/c.F/*</bind>*/(
}
void F(int x) { }
}
static class E
{
internal static void F(this object x, object y) { }
}
}
static class E
{
internal static void F(this object x, object y, object z) { }
}";
compilation = CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N2").GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void object.F(object y)",
"void object.F()",
"void object.F(object y, object z)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void C.F(int x)",
"void object.F(object y)",
"void object.F()",
"void object.F(object y, object z)");
// Multiple scopes, no instance methods.
sourceCode =
@"namespace N
{
class C
{
static void M(C c)
{
/*<bind>*/c.F/*</bind>*/(
}
}
static class E
{
internal static void F(this object x, object y) { }
}
}
static class E
{
internal static void F(this object x, object y, object z) { }
}";
compilation = CreateCompilation(source: sourceCode);
type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N").GetMember<INamedTypeSymbol>("C");
tree = compilation.SyntaxTrees.First();
model = compilation.GetSemanticModel(tree);
expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree));
symbols = model.GetMemberGroup(expr);
Utils.CheckISymbols(symbols,
"void object.F(object y)",
"void object.F(object y, object z)");
symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true);
Utils.CheckISymbols(symbols,
"void object.F(object y)",
"void object.F(object y, object z)");
}
[ClrOnlyFact]
public void PropertyGroup()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Class A
Property P(Optional x As Integer = 0) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Property P(x As Integer, y As Integer) As Integer
Get
Return Nothing
End Get
Set
End Set
End Property
Property P(x As Integer, y As String) As String
Get
Return Nothing
End Get
Set
End Set
End Property
End Class";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped);
// Assignment (property group).
var source2 =
@"class B
{
static void M(A a)
{
/*<bind>*/a.P/*</bind>*/[1, null] = string.Empty;
}
}";
var compilation = CreateCompilation(source2, new[] { reference1 });
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.MemberGroup,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Assignment (property access).
source2 =
@"class B
{
static void M(A a)
{
/*<bind>*/a.P[1, null]/*</bind>*/ = string.Empty;
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.MemberGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Object initializer.
source2 =
@"class B
{
static A F = new A() { /*<bind>*/P/*</bind>*/ = 1 };
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object A.P[int x = 0]");
Utils.CheckISymbols(semanticInfo.MemberGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Incomplete reference, overload resolution failure (property group).
source2 =
@"class B
{
static void M(A a)
{
var o = /*<bind>*/a.P/*</bind>*/[1, a
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MemberGroup,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
// Incomplete reference, overload resolution failure (property access).
source2 =
@"class B
{
static void M(A a)
{
var o = /*<bind>*/a.P[1, a/*</bind>*/
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Assert.Null(semanticInfo.Symbol);
Utils.CheckISymbols(semanticInfo.MemberGroup);
Utils.CheckISymbols(semanticInfo.CandidateSymbols,
"object A.P[int x = 0]",
"int A.P[int x, int y]",
"string A.P[int x, string y]");
}
[ClrOnlyFact]
public void PropertyGroupOverloadsOverridesHides()
{
var source1 =
@"Imports System
Imports System.Runtime.InteropServices
<Assembly: PrimaryInteropAssembly(0, 0)>
<Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")>
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")>
Public Class A
Overridable ReadOnly Property P1(index As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P2(index As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P2(x As Object, y As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P3(index As Object) As Object
Get
Return Nothing
End Get
End Property
ReadOnly Property P3(x As Object, y As Object) As Object
Get
Return Nothing
End Get
End Property
End Class
<ComImport()>
<Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E212"")>
Public Class B
Inherits A
Overrides ReadOnly Property P1(index As Object) As Object
Get
Return Nothing
End Get
End Property
Shadows ReadOnly Property P2(index As String) As Object
Get
Return Nothing
End Get
End Property
End Class";
var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped);
// Overridden property.
var source2 =
@"class C
{
static object F(B b)
{
return /*<bind>*/b.P1/*</bind>*/[null];
}
}";
var compilation = CreateCompilation(source2, new[] { reference1 });
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object B.P1[object index]");
Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P1[object index]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Hidden property.
source2 =
@"class C
{
static object F(B b)
{
return /*<bind>*/b.P2/*</bind>*/[null];
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object B.P2[string index]");
Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P2[string index]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
// Overloaded property.
source2 =
@"class C
{
static object F(B b)
{
return /*<bind>*/b.P3/*</bind>*/[null];
}
}";
compilation = CreateCompilation(source2, new[] { reference1 });
semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation);
Utils.CheckSymbol(semanticInfo.Symbol, "object A.P3[object index]");
Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P3[object index]", "object A.P3[object x, object y]");
Utils.CheckISymbols(semanticInfo.CandidateSymbols);
}
[WorkItem(538859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538859")]
[Fact]
public void ThisExpression()
{
string sourceCode = @"
class C
{
void M()
{
/*<bind>*/this/*</bind>*/.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C this", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538143")]
[Fact]
public void GetSemanticInfoOfNull()
{
var compilation = CreateCompilation("");
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetConstantValue((ExpressionSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ConstructorInitializerSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ConstructorInitializerSyntax)null));
Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ConstructorInitializerSyntax)null));
}
[WorkItem(537860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537860")]
[Fact]
public void UsingNamespaceName()
{
string sourceCode = @"
using /*<bind>*/System/*</bind>*/;
class Test
{
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3017, "DevDiv_Projects/Roslyn")]
[Fact]
public void VariableUsedInForInit()
{
string sourceCode = @"
class Test
{
void Fill()
{
for (int i = 0; /*<bind>*/i/*</bind>*/ < 10 ; i++ )
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527269")]
[Fact]
public void NullLiteral()
{
string sourceCode = @"
class Test
{
public static void Main()
{
string s = /*<bind>*/null/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[WorkItem(3019, "DevDiv_Projects/Roslyn")]
[Fact]
public void PostfixIncrement()
{
string sourceCode = @"
class Test
{
public static void Main()
{
int i = 10;
/*<bind>*/i++/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 System.Int32.op_Increment(System.Int32 value)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3199, "DevDiv_Projects/Roslyn")]
[Fact]
public void ConditionalOrExpr()
{
string sourceCode = @"
class Program
{
static void T1()
{
bool result = /*<bind>*/true || true/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[WorkItem(3222, "DevDiv_Projects/Roslyn")]
[Fact]
public void ConditionalOperExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
int i = /*<bind>*/(true ? 0 : 1)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(0, semanticInfo.ConstantValue);
}
[WorkItem(3223, "DevDiv_Projects/Roslyn")]
[Fact]
public void DefaultValueExpr()
{
string sourceCode = @"
class Test
{
static void Main(string[] args)
{
int s = /*<bind>*/default(int)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(0, semanticInfo.ConstantValue);
}
[WorkItem(537979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537979")]
[Fact]
public void StringConcatWithInt()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
string str = /*<bind>*/""Count value is: "" + 5/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3226, "DevDiv_Projects/Roslyn")]
[Fact]
public void StringConcatWithIntAndNullableInt()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
string str = /*<bind>*/""Count value is: "" + (int?) 10 + 5/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3234, "DevDiv_Projects/Roslyn")]
[Fact]
public void AsOper()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
object o = null;
string str = /*<bind>*/o as string/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537983")]
[Fact]
public void AddWithUIntAndInt()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
uint ui = 0;
ulong ui2 = /*<bind>*/ui + 5/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.UInt32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.UInt64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.UInt32 System.UInt32.op_Addition(System.UInt32 left, System.UInt32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527314")]
[Fact()]
public void AddExprWithNullableUInt64AndInt32()
{
string sourceCode = @"
public class Test
{
public static void Main(string[] args)
{
ulong? ui = 0;
ulong? ui2 = /*<bind>*/ui + 5/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.UInt64?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.UInt64?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("ulong.operator +(ulong, ulong)", semanticInfo.Symbol.ToString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3248, "DevDiv_Projects/Roslyn")]
[Fact]
public void NegatedIsExpr()
{
string sourceCode = @"
using System;
public class Test
{
public static void Main()
{
Exception e = new Exception();
bool bl = /*<bind>*/!(e is DivideByZeroException)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Boolean.op_LogicalNot(System.Boolean value)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3249, "DevDiv_Projects/Roslyn")]
[Fact]
public void IsExpr()
{
string sourceCode = @"
using System;
public class Test
{
public static void Main()
{
Exception e = new Exception();
bool bl = /*<bind>*/ (e is DivideByZeroException) /*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527324")]
[Fact]
public void ExceptionCatchVariable()
{
string sourceCode = @"
using System;
public class Test
{
public static void Main()
{
try
{
}
catch (Exception e)
{
bool bl = (/*<bind>*/e/*</bind>*/ is DivideByZeroException) ;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Exception", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Exception", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Exception e", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3478, "DevDiv_Projects/Roslyn")]
[Fact]
public void GenericInvocation()
{
string sourceCode = @"
class Program {
public static void Ref<T>(T array)
{
}
static void Main()
{
/*<bind>*/Ref<object>(null)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void Program.Ref<System.Object>(System.Object array)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538039")]
[Fact]
public void GlobalAliasQualifiedName()
{
string sourceCode = @"
namespace N1
{
interface I1
{
void Method();
}
}
namespace N2
{
class Test : N1.I1
{
void /*<bind>*/global::N1.I1/*</bind>*/.Method()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.I1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("N1.I1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.I1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527363")]
[Fact]
public void ArrayInitializer()
{
string sourceCode = @"
class Test
{
static void Main()
{
int[] arr = new int[] /*<bind>*/{5}/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538041")]
[Fact]
public void AliasQualifiedName()
{
string sourceCode = @"
using NSA = A;
namespace A
{
class Goo {}
}
namespace B
{
class Test
{
class NSA
{
}
static void Main()
{
/*<bind>*/NSA::Goo/*</bind>*/ goo = new NSA::Goo();
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A.Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A.Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A.Goo", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538021")]
[Fact]
public void EnumToStringInvocationExpr()
{
string sourceCode = @"
using System;
enum E { Red, Blue, Green}
public class MainClass
{
public static int Main ()
{
E e = E.Red;
string s = /*<bind>*/e.ToString()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String System.Enum.ToString()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538026")]
[Fact]
public void ExplIfaceMethInvocationExpr()
{
string sourceCode = @"
namespace N1
{
interface I1
{
int Method();
}
}
namespace N2
{
class Test : N1.I1
{
int N1.I1.Method()
{
return 5;
}
static int Main()
{
Test t = new Test();
if (/*<bind>*/((N1.I1)t).Method()/*</bind>*/ != 5)
return 1;
return 0;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 N1.I1.Method()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538027")]
[Fact]
public void InvocExprWithAliasIdentifierNameSameAsType()
{
string sourceCode = @"
using N1 = NGoo;
namespace NGoo
{
class Goo
{
public static void method() { }
}
}
namespace N2
{
class N1 { }
class Test
{
static void Main()
{
/*<bind>*/N1::Goo.method()/*</bind>*/;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void NGoo.Goo.method()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3498, "DevDiv_Projects/Roslyn")]
[Fact]
public void BaseAccessMethodInvocExpr()
{
string sourceCode = @"
using System;
public class BaseClass
{
public virtual void MyMeth()
{
}
}
public class MyClass : BaseClass
{
public override void MyMeth()
{
/*<bind>*/base.MyMeth()/*</bind>*/;
}
public static void Main()
{
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void BaseClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")]
[Fact]
public void OverloadResolutionForVirtualMethods()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
D d = new D();
string s = ""hello""; long l = 1;
/*<bind>*/d.goo(ref s, l, l)/*</bind>*/;
}
}
public class B
{
// Should bind to this method.
public virtual int goo(ref string x, long y, long z)
{
Console.WriteLine(""Base: goo(ref string x, long y, long z)"");
return 0;
}
public virtual void goo(ref string x, params long[] y)
{
Console.WriteLine(""Base: goo(ref string x, params long[] y)"");
}
}
public class D: B
{
// Roslyn erroneously binds to this override.
// Roslyn binds to the correct method above if you comment out this override.
public override void goo(ref string x, params long[] y)
{
Console.WriteLine(""Derived: goo(ref string x, params long[] y)"");
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 B.goo(ref System.String x, System.Int64 y, System.Int64 z)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")]
[Fact]
public void OverloadResolutionForVirtualMethods2()
{
string sourceCode = @"
using System;
class Program
{
static void Main()
{
D d = new D();
int i = 1;
/*<bind>*/d.goo(i, i)/*</bind>*/;
}
}
public class B
{
public virtual int goo(params int[] x)
{
Console.WriteLine(""""Base: goo(params int[] x)"""");
return 0;
}
public virtual void goo(params object[] x)
{
Console.WriteLine(""""Base: goo(params object[] x)"""");
}
}
public class D: B
{
public override void goo(params object[] x)
{
Console.WriteLine(""""Derived: goo(params object[] x)"""");
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 B.goo(params System.Int32[] x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ThisInStaticMethod()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/this/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("Program", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("Program this", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Constructor1()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/A/*</bind>*/(4);
}
}
class A
{
public A() { }
public A(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void Constructor2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new A(4)/*</bind>*/;
}
}
class A
{
public A() { }
public A(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("A..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void FailedOverloadResolution1()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
/*<bind>*/A.f(o)/*</bind>*/;
}
}
class A
{
public void f(int x, int y) { }
public void f(string z) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void FailedOverloadResolution2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
A./*<bind>*/f/*</bind>*/(o);
}
}
class A
{
public void f(int x, int y) { }
public void f(string z) { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void A.f(System.String z)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541745")]
[Fact]
public void FailedOverloadResolution3()
{
string sourceCode = @"
class C
{
public int M { get; set; }
}
static class Extensions1
{
public static int M(this C c) { return 0; }
}
static class Extensions2
{
public static int M(this C c) { return 0; }
}
class Goo
{
void M()
{
C c = new C();
/*<bind>*/c.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("System.Int32 C.M()", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.Int32 C.M()", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542833")]
[Fact]
public void FailedOverloadResolution4()
{
string sourceCode = @"
class C
{
public int M;
}
static class Extensions
{
public static int M(this C c, int i) { return 0; }
}
class Goo
{
void M()
{
C c = new C();
/*<bind>*/c.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SucceededOverloadResolution1()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
/*<bind>*/A.f(""hi"")/*</bind>*/;
}
}
class A
{
public static void f(int x, int y) { }
public static int f(string z) { return 3; }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SucceededOverloadResolution2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = null;
A./*<bind>*/f/*</bind>*/(""hi"");
}
}
class A
{
public static void f(int x, int y) { }
public static int f(string z) { return 3; }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 A.f(System.String z)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541878")]
[Fact]
public void TestCandidateReasonForInaccessibleMethod()
{
string sourceCode = @"
class Test
{
class NestedTest
{
static void Method1()
{
}
}
static void Main()
{
/*<bind>*/NestedTest.Method1()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void Test.NestedTest.Method1()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
}
[WorkItem(541879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541879")]
[Fact]
public void InaccessibleTypeInObjectCreationExpression()
{
string sourceCode = @"
class Test
{
class NestedTest
{
class NestedNestedTest
{
}
}
static void Main()
{
var nnt = /*<bind>*/new NestedTest.NestedNestedTest()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Test.NestedTest.NestedNestedTest..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
}
[WorkItem(541883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541883")]
[Fact]
public void InheritedMemberHiding()
{
string sourceCode = @"
public class A
{
public static int m() { return 1; }
}
public class B : A
{
public static int m() { return 5; }
public static void Main1()
{
/*<bind>*/m/*</bind>*/(10);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 B.m()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 B.m()", sortedMethodGroup[0].ToTestDisplayString());
}
[WorkItem(538106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538106")]
[Fact]
public void UsingAliasNameSystemInvocExpr()
{
string sourceCode = @"
using System = MySystem.IO.StreamReader;
namespace N1
{
using NullStreamReader = System::NullStreamReader;
class Test
{
static int Main()
{
NullStreamReader nr = new NullStreamReader();
/*<bind>*/nr.ReadLine()/*</bind>*/;
return 0;
}
}
}
namespace MySystem
{
namespace IO
{
namespace StreamReader
{
public class NullStreamReader
{
public string ReadLine() { return null; }
}
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String MySystem.IO.StreamReader.NullStreamReader.ReadLine()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538109")]
[Fact]
public void InterfaceMethodImplInvocExpr()
{
string sourceCode = @"
interface ISomething
{
string ToString();
}
class A : ISomething
{
string ISomething.ToString()
{
return null;
}
}
class Test
{
static void Main()
{
ISomething isome = new A();
/*<bind>*/isome.ToString()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String ISomething.ToString()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538112")]
[Fact]
public void MemberAccessMethodWithNew()
{
string sourceCode = @"
public class MyBase
{
public void MyMeth()
{
}
}
public class MyClass : MyBase
{
new public void MyMeth()
{
}
public static void Main()
{
MyClass test = new MyClass();
/*<bind>*/test.MyMeth/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void MyClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void MyClass.MyMeth()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527386")]
[Fact]
public void MethodGroupWithStaticInstanceSameName()
{
string sourceCode = @"
class D
{
public static void M2(int x, int y)
{
}
public void M2(int x)
{
}
}
class C
{
public static void Main()
{
D d = new D();
/*<bind>*/d.M2/*</bind>*/(5);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void D.M2(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void D.M2(System.Int32 x)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void D.M2(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538123")]
[Fact]
public void VirtualOverriddenMember()
{
string sourceCode = @"
public class C1
{
public virtual void M1()
{
}
}
public class C2:C1
{
public override void M1()
{
}
}
public class Test
{
static void Main()
{
C2 c2 = new C2();
/*<bind>*/c2.M1/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void C2.M1()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C2.M1()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538125")]
[Fact]
public void AbstractOverriddenMember()
{
string sourceCode = @"
public abstract class AbsClass
{
public abstract void Test();
}
public class TestClass : AbsClass
{
public override void Test() { }
public static void Main()
{
TestClass tc = new TestClass();
/*<bind>*/tc.Test/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void TestClass.Test()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void TestClass.Test()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DiamondInheritanceMember()
{
string sourceCode = @"
public interface IB { void M(); }
public interface IM1 : IB {}
public interface IM2 : IB {}
public interface ID : IM1, IM2 {}
public class Program
{
public static void Main()
{
ID id = null;
/*<bind>*/id.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
// We must ensure that the method is only found once, even though there are two paths to it.
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void IB.M()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void IB.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InconsistentlyHiddenMember()
{
string sourceCode = @"
public interface IB { void M(); }
public interface IL : IB {}
public interface IR : IB { new void M(); }
public interface ID : IR, IL {}
public class Program
{
public static void Main()
{
ID id = null;
/*<bind>*/id.M/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
// Even though there is a "path" from ID to IB.M via IL on which IB.M is not hidden,
// it is still hidden because *any possible hiding* hides the method.
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void IR.M()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void IR.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538138")]
[Fact]
public void ParenExprWithMethodInvocExpr()
{
string sourceCode = @"
class Test
{
public static int Meth1()
{
return 9;
}
public static void Main()
{
int var1 = /*<bind>*/(Meth1())/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Test.Meth1()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(527397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527397")]
[Fact()]
public void ExplicitIdentityCastExpr()
{
string sourceCode = @"
class Test
{
public static void Main()
{
int i = 10;
object j = /*<bind>*/(int)i/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(3652, "DevDiv_Projects/Roslyn")]
[WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")]
[WorkItem(543619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543619")]
[Fact()]
public void OutOfBoundsConstCastToByte()
{
string sourceCode = @"
class Test
{
public static void Main()
{
byte j = unchecked(/*<bind>*/(byte)-123/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal((byte)133, semanticInfo.ConstantValue);
}
[WorkItem(538160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538160")]
[Fact]
public void InsideCollectionsNamespace()
{
string sourceCode = @"
using System;
namespace Collections
{
public class Test
{
public static /*<bind>*/void/*</bind>*/ Main()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Void", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538161")]
[Fact]
public void ErrorTypeNameSameAsVariable()
{
string sourceCode = @"
public class A
{
public static void RunTest()
{
/*<bind>*/B/*</bind>*/ B = new B();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotATypeOrNamespace, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("B B", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Local, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537117")]
[WorkItem(537127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537127")]
[Fact]
public void SystemNamespace()
{
string sourceCode = @"
namespace System
{
class A
{
/*<bind>*/System/*</bind>*/.Exception c;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537118")]
[Fact]
public void SystemNamespace2()
{
string sourceCode = @"
namespace N1
{
namespace N2
{
public class A1 { }
}
public class A2
{
/*<bind>*/N1.N2.A1/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.N2.A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.N2.A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.N2.A1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537119")]
[Fact]
public void SystemNamespace3()
{
string sourceCode = @"
class H<T>
{
}
class A
{
}
namespace N1
{
public class A1
{
/*<bind>*/H<A>/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("H<A>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("H<A>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("H<A>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537124")]
[Fact]
public void SystemNamespace4()
{
string sourceCode = @"
using System;
class H<T>
{
}
class H<T1, T2>
{
}
class A
{
}
namespace N1
{
public class A1
{
/*<bind>*/H<H<A>, H<A>>/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("H<H<A>, H<A>>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("H<H<A>, H<A>>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("H<H<A>, H<A>>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537160")]
[Fact]
public void SystemNamespace5()
{
string sourceCode = @"
namespace N1
{
namespace N2
{
public class A2
{
public class A1 { }
/*<bind>*/N1.N2.A2.A1/*</bind>*/ a;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.N2.A2.A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.N2.A2.A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.N2.A2.A1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537161")]
[Fact]
public void SystemNamespace6()
{
string sourceCode = @"
namespace N1
{
class NC1
{
public class A1 { }
}
public class A2
{
/*<bind>*/N1.NC1.A1/*</bind>*/ a;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("N1.NC1.A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.NC1.A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.NC1.A1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537340")]
[Fact]
public void LeftOfDottedTypeName()
{
string sourceCode = @"
class Main
{
A./*<bind>*/B/*</bind>*/ x; // this refers to the B within A.
}
class A {
public class B {}
}
class B {}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A.B", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537592")]
[Fact]
public void Parameters()
{
string sourceCode = @"
class C
{
void M(DateTime dt)
{
/*<bind>*/dt/*</bind>*/.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("DateTime", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("DateTime", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("DateTime dt", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
// TODO: This should probably have a candidate symbol!
[WorkItem(527212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527212")]
[Fact]
public void FieldMemberOfConstructedType()
{
string sourceCode = @"
class C<T> {
public T Field;
}
class D {
void M() {
new C<int>./*<bind>*/Field/*</bind>*/.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C<System.Int32>.Field", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("C<System.Int32>.Field", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
// Should bind to "field" with a candidateReason (not a typeornamespace>)
Assert.NotEqual(CandidateReason.None, semanticInfo.CandidateReason);
Assert.NotEqual(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(537593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537593")]
[Fact]
public void Constructor()
{
string sourceCode = @"
class C
{
public C() { /*<bind>*/new C()/*</bind>*/.ToString(); }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538046")]
[Fact]
public void TypeNameInTypeThatMatchesNamespace()
{
string sourceCode = @"
namespace T
{
class T
{
void M()
{
/*<bind>*/T/*</bind>*/.T T = new T.T();
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("T.T", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("T.T", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("T.T", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538267")]
[Fact]
public void RHSExpressionInTryParent()
{
string sourceCode = @"
using System;
public class Test
{
static int Main()
{
try
{
object obj = /*<bind>*/null/*</bind>*/;
}
catch {}
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")]
[Fact]
public void GenericArgumentInBase1()
{
string sourceCode = @"
public class X
{
public interface Z { }
}
class A<T>
{
public class X { }
}
class B : A<B.Y./*<bind>*/Z/*</bind>*/>
{
public class Y : X { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("B.Y.Z", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("B.Y.Z", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")]
[Fact]
public void GenericArgumentInBase2()
{
string sourceCode = @"
public class X
{
public interface Z { }
}
class A<T>
{
public class X { }
}
class B : /*<bind>*/A<B.Y.Z>/*</bind>*/
{
public class Y : X { }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("A<B.Y.Z>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A<B.Y.Z>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A<B.Y.Z>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538097")]
[Fact]
public void InvokedLocal1()
{
string sourceCode = @"
class C
{
static void Goo()
{
int x = 10;
/*<bind>*/x/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538318")]
[Fact]
public void TooManyConstructorArgs()
{
string sourceCode = @"
class C
{
C() {}
void M()
{
/*<bind>*/new C(null
/*</bind>*/ }
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(538185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538185")]
[Fact]
public void NamespaceAndFieldSameName1()
{
string sourceCode = @"
class C
{
void M()
{
/*<bind>*/System/*</bind>*/.String x = F();
}
string F()
{
return null;
}
public int System;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void PEProperty()
{
string sourceCode = @"
class C
{
void M(string s)
{
/*<bind>*/s.Length/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 System.String.Length { get; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NotPresentGenericType1()
{
string sourceCode = @"
class Class { void Test() { /*<bind>*/List<int>/*</bind>*/ l; } }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NotPresentGenericType2()
{
string sourceCode = @"
class Class {
/*<bind>*/List<int>/*</bind>*/ Test() { return null;}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BadArityConstructorCall()
{
string sourceCode = @"
class C<T1>
{
public void Test()
{
C c = new /*<bind>*/C/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C<T1>", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BadArityConstructorCall2()
{
string sourceCode = @"
class C<T1>
{
public void Test()
{
C c = /*<bind>*/new C()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("C<T1>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C<T1>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C<T1>..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C<T1>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void UnresolvedBaseConstructor()
{
string sourceCode = @"
class C : B {
public C(int i) /*<bind>*/: base(i)/*</bind>*/ { }
public C(string j, string k) : base() { }
}
class B {
public B(string a, string b) { }
public B() { }
int i;
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("B..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("B..ctor(System.String a, System.String b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BoundBaseConstructor()
{
string sourceCode = @"
class C : B {
public C(int i) /*<bind>*/: base(""hi"", ""hello"")/*</bind>*/ { }
public C(string j, string k) : base() { }
}
class B
{
public B(string a, string b) { }
public B() { }
int i;
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("B..ctor(System.String a, System.String b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540998")]
[Fact]
public void DeclarationWithinSwitchStatement()
{
string sourceCode =
@"class C
{
static void M(int i)
{
switch (i)
{
case 0:
string name = /*<bind>*/null/*</bind>*/;
if (name != null)
{
}
break;
}
}
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.NotNull(semanticInfo);
}
[WorkItem(537573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537573")]
[Fact]
public void UndeclaredTypeAndCheckContainingSymbol()
{
string sourceCode = @"
class C1
{
void M()
{
/*<bind>*/F/*</bind>*/ f;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("F", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("F", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.Equal(SymbolKind.Namespace, semanticInfo.Type.ContainingSymbol.Kind);
Assert.True(((INamespaceSymbol)semanticInfo.Type.ContainingSymbol).IsGlobalNamespace);
}
[WorkItem(538538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538538")]
[Fact]
public void AliasQualifier()
{
string sourceCode = @"
using X = A;
namespace A.B { }
namespace N
{
using /*<bind>*/X/*</bind>*/::B;
class X { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("X=A", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AliasQualifier2()
{
string sourceCode = @"
using S = System.String;
{
class X
{
void Goo()
{
string x;
x = /*<bind>*/S/*</bind>*/.Empty;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Equal("S=System.String", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal("String", aliasInfo.Target.Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void PropertyAccessor()
{
string sourceCode = @"
class C
{
private object p = null;
internal object P { set { p = /*<bind>*/value/*</bind>*/; } }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Object value", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void IndexerAccessorValue()
{
string sourceCode =
@"class C
{
string[] values = new string[10];
internal string this[int i]
{
get { return values[i]; }
set { values[i] = /*<bind>*/value/*</bind>*/; }
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("System.String value", semanticInfo.Symbol.ToTestDisplayString());
}
[Fact]
public void IndexerAccessorParameter()
{
string sourceCode =
@"class C
{
string[] values = new string[10];
internal string this[short i]
{
get { return values[/*<bind>*/i/*</bind>*/]; }
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString());
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("System.Int16 i", semanticInfo.Symbol.ToTestDisplayString());
}
[Fact]
public void IndexerAccessNamedParameter()
{
string sourceCode =
@"class C
{
string[] values = new string[10];
internal string this[short i]
{
get { return values[i]; }
}
void Method()
{
string s = this[/*<bind>*/i/*</bind>*/: 0];
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
var symbol = semanticInfo.Symbol;
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.True(symbol.ContainingSymbol.Kind == SymbolKind.Property && ((IPropertySymbol)symbol.ContainingSymbol).IsIndexer);
Assert.Equal("System.Int16 i", symbol.ToTestDisplayString());
}
[Fact]
public void LocalConstant()
{
string sourceCode = @"
class C
{
static void M()
{
const int i = 1;
const int j = i + 1;
const int k = /*<bind>*/j/*</bind>*/ - 2;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 j", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2, semanticInfo.ConstantValue);
var symbol = (ILocalSymbol)semanticInfo.Symbol;
Assert.True(symbol.HasConstantValue);
Assert.Equal(2, symbol.ConstantValue);
}
[Fact]
public void FieldConstant()
{
string sourceCode = @"
class C
{
const int i = 1;
const int j = i + 1;
static void M()
{
const int k = /*<bind>*/j/*</bind>*/ - 2;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 C.j", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2, semanticInfo.ConstantValue);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.Equal("j", symbol.Name);
Assert.True(symbol.HasConstantValue);
Assert.Equal(2, symbol.ConstantValue);
}
[Fact]
public void FieldInitializer()
{
string sourceCode = @"
class C
{
int F = /*<bind>*/G() + 1/*</bind>*/;
static int G()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void EnumConstant()
{
string sourceCode = @"
enum E { A, B, C, D = B }
class C
{
static void M(E e)
{
M(/*<bind>*/E.C/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2, semanticInfo.ConstantValue);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("C", symbol.Name);
Assert.True(symbol.HasConstantValue);
Assert.Equal(2, symbol.ConstantValue);
}
[Fact]
public void BadEnumConstant()
{
string sourceCode = @"
enum E { W = Z, X, Y }
class C
{
static void M(E e)
{
M(/*<bind>*/E.Y/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.Y", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("Y", symbol.Name);
Assert.False(symbol.HasConstantValue);
}
[Fact]
public void CircularEnumConstant01()
{
string sourceCode = @"
enum E { A = B, B }
class C
{
static void M(E e)
{
M(/*<bind>*/E.B/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("B", symbol.Name);
Assert.False(symbol.HasConstantValue);
}
[Fact]
public void CircularEnumConstant02()
{
string sourceCode = @"
enum E { A = 10, B = C, C, D }
class C
{
static void M(E e)
{
M(/*<bind>*/E.D/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.D", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("D", symbol.Name);
Assert.False(symbol.HasConstantValue);
}
[Fact]
public void EnumInitializer()
{
string sourceCode = @"
enum E { A, B = 3 }
enum F { C, D = 1 + /*<bind>*/E.B/*</bind>*/ }
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("E", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(3, semanticInfo.ConstantValue);
var symbol = (IFieldSymbol)semanticInfo.Symbol;
Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol());
Assert.Equal("B", symbol.Name);
Assert.True(symbol.HasConstantValue);
Assert.Equal(3, symbol.ConstantValue);
}
[Fact]
public void ParameterOfExplicitInterfaceImplementation()
{
string sourceCode = @"
class Class : System.IFormattable
{
string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider)
{
return /*<bind>*/format/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String format", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BaseConstructorInitializer()
{
string sourceCode = @"
class Class
{
Class(int x) : this(/*<bind>*/x/*</bind>*/ , x) { }
Class(int x, int y) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.ContainingSymbol.Kind);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind);
}
[WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")]
[WorkItem(527831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527831")]
[WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")]
[Fact]
public void InaccessibleMethodGroup()
{
string sourceCode = @"
class C
{
private static void M(long i) { }
private static void M(int i) { }
}
class D
{
void Goo()
{
C./*<bind>*/M/*</bind>*/(1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal("void C.M(System.Int64 i)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("void C.M(System.Int64 i)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_Constructors_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = /*<bind>*/new Class1(3, 7)/*</bind>*/;
}
}
class Class1
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InaccessibleMethodGroup_Constructors_ImplicitObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
Class1 x = /*<bind>*/new(3, 7)/*</bind>*/;
}
}
class Class1
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_Constructors_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = new /*<bind>*/Class1/*</bind>*/(3, 7);
}
}
class Class1
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_AttributeSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1(3, 7)/*</bind>*/]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleMethodGroup_Attribute_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1/*</bind>*/(3, 7)]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
protected Class1(int x) { }
private Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = /*<bind>*/new Class1(3, 7)/*</bind>*/;
}
}
class Class1
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
public static void Main(string[] args)
{
var x = new /*<bind>*/Class1/*</bind>*/(3, 7);
}
}
class Class1
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_AttributeSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1(3, 7)/*</bind>*/]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")]
[Fact]
public void InaccessibleConstructorsFiltered_Attribute_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/Class1/*</bind>*/(3, 7)]
public static void Main(string[] args)
{
}
}
class Class1 : Attribute
{
protected Class1() { }
public Class1(int x) { }
public Class1(int a, long b) { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")]
[Fact]
public void SyntaxErrorInReceiver()
{
string sourceCode = @"
public delegate int D(int x);
public class C
{
public C(int i) { }
public void M(D d) { }
}
class Main
{
void Goo(int a)
{
new C(a.).M(x => /*<bind>*/x/*</bind>*/);
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")]
[Fact]
public void SyntaxErrorInReceiverWithExtension()
{
string sourceCode = @"
public delegate int D(int x);
public static class CExtensions
{
public static void M(this C c, D d) { }
}
public class C
{
public C(int i) { }
}
class Main
{
void Goo(int a)
{
new C(a.).M(x => /*<bind>*/x/*</bind>*/);
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")]
[Fact]
public void NonStaticInstanceMismatchMethodGroup()
{
string sourceCode = @"
class C
{
public static int P { get; set; }
}
class D
{
void Goo()
{
C./*<bind>*/set_P/*</bind>*/(1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.P.set", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(MethodKind.PropertySet, ((IMethodSymbol)sortedCandidates[0]).MethodKind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.P.set", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540360")]
[Fact]
public void DuplicateTypeName()
{
string sourceCode = @"
struct C { }
class C
{
public static void M() { }
}
enum C { A, B }
class D
{
static void Main()
{
/*<bind>*/C/*</bind>*/.M();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("C", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal("C", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[2].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void IfCondition()
{
string sourceCode = @"
class C
{
void M(int x)
{
if (/*<bind>*/x == 10/*</bind>*/) {}
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ForCondition()
{
string sourceCode = @"
class C
{
void M(int x)
{
for (int i = 0; /*<bind>*/i < 10/*</bind>*/; i = i + 1) { }
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(539925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539925")]
[Fact]
public void LocalIsFromSource()
{
string sourceCode = @"
class C
{
void M()
{
int x = 1;
int y = /*<bind>*/x/*</bind>*/;
}
}
";
var compilation = CreateCompilation(sourceCode);
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(compilation);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.True(semanticInfo.Symbol.GetSymbol().IsFromCompilation(compilation));
}
[WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")]
[Fact]
public void InEnumElementInitializer()
{
string sourceCode = @"
class C
{
public const int x = 1;
}
enum E
{
q = /*<bind>*/C.x/*</bind>*/,
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")]
[Fact]
public void InEnumOfByteElementInitializer()
{
string sourceCode = @"
class C
{
public const int x = 1;
}
enum E : byte
{
q = /*<bind>*/C.x/*</bind>*/,
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540672")]
[Fact]
public void LambdaExprWithErrorTypeInObjectCreationExpression()
{
var text = @"
class Program
{
static int Main()
{
var d = /*<bind>*/() => { if (true) return new X(); else return new Y(); }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(text);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[Fact]
public void LambdaExpression()
{
string sourceCode = @"
using System;
public class TestClass
{
public static void Main()
{
Func<string, int> f = /*<bind>*/str => 10/*</bind>*/ ;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Func<System.String, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol);
Assert.Equal(1, lambdaSym.Parameters.Length);
Assert.Equal("str", lambdaSym.Parameters[0].Name);
Assert.Equal("System.String", lambdaSym.Parameters[0].Type.ToTestDisplayString());
Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString());
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void UnboundLambdaExpression()
{
string sourceCode = @"
using System;
public class TestClass
{
public static void Main()
{
object f = /*<bind>*/str => 10/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol);
Assert.Equal(1, lambdaSym.Parameters.Length);
Assert.Equal("str", lambdaSym.Parameters[0].Name);
Assert.Equal(TypeKind.Error, lambdaSym.Parameters[0].Type.TypeKind);
Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString());
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540650")]
[Fact]
public void TypeOfExpression()
{
string sourceCode = @"
class C
{
static void Main()
{
System.Console.WriteLine(/*<bind>*/typeof(C)/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<TypeOfExpressionSyntax>(sourceCode);
Assert.Equal("System.Type", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_If()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
if (c)
int j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_For()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
for (; c; c = !c)
label: /*<bind>*/c/*</bind>*/ = false;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_While()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
while (c)
int j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_ForEach()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
foreach (string s in args)
label: /*<bind>*/c/*</bind>*/ = false;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_Else()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
if (c);
else
long j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_Do()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
do
label: /*<bind>*/c/*</bind>*/ = false;
while(c);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_Using()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
using(null)
long j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void LabeledEmbeddedStatement_Lock()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
lock(this)
label: /*<bind>*/c/*</bind>*/ = false;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")]
[Fact]
public void DeclarationEmbeddedStatement_Fixed()
{
string sourceCode = @"
unsafe class Program
{
static void Main(string[] args)
{
bool c = true;
fixed (bool* p = &c)
int j = /*<bind>*/43/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(43, semanticInfo.ConstantValue);
}
[WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")]
[Fact]
public void BindLiteralCastToDouble()
{
string sourceCode = @"
class MyClass
{
double dbl = /*<bind>*/1/*</bind>*/ ;
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540803")]
[Fact]
public void BindDefaultOfVoidExpr()
{
string sourceCode = @"
class C
{
void M()
{
return /*<bind>*/default(void)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(SpecialType.System_Void, semanticInfo.Type.SpecialType);
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void GetSemanticInfoForBaseConstructorInitializer()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: base()/*</bind>*/ { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void GetSemanticInfoForThisConstructorInitializer()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: this(1)/*</bind>*/ { }
C(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")]
[Fact]
public void ThisStaticConstructorInitializer()
{
string sourceCode = @"
class MyClass
{
static MyClass()
/*<bind>*/: this()/*</bind>*/
{
intI = 2;
}
public MyClass() { }
static int intI = 1;
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("MyClass..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")]
[Fact]
public void IncompleteForEachWithArrayCreationExpr()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
foreach (var f in new int[] { /*<bind>*/5/*</bind>*/
{
Console.WriteLine(f);
}
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(5, (int)semanticInfo.ConstantValue.Value);
}
[WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")]
[Fact]
public void EmptyStatementInForEach()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
foreach (var a in /*<bind>*/args/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, ((IArrayTypeSymbol)semanticInfo.Type).ElementType.SpecialType);
// CONSIDER: we could conceivable use the foreach collection type (vs the type of the collection expr).
Assert.Equal(SpecialType.System_Collections_IEnumerable, semanticInfo.ConvertedType.SpecialType);
Assert.Equal("args", semanticInfo.Symbol.Name);
}
[WorkItem(540922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540922")]
[WorkItem(541030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541030")]
[Fact]
public void ImplicitlyTypedForEachIterationVariable()
{
string sourceCode = @"
class Program
{
static void Main(string[] args)
{
foreach (/*<bind>*/var/*</bind>*/ a in args);
}
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
var symbol = semanticInfo.Symbol;
Assert.Equal(SymbolKind.NamedType, symbol.Kind);
Assert.Equal(SpecialType.System_String, ((ITypeSymbol)symbol).SpecialType);
}
[Fact]
public void ForEachCollectionConvertedType()
{
// Arrays don't actually use IEnumerable, but that's the spec'd behavior.
CheckForEachCollectionConvertedType("int[]", "System.Int32[]", "System.Collections.IEnumerable");
CheckForEachCollectionConvertedType("int[,]", "System.Int32[,]", "System.Collections.IEnumerable");
// Strings don't actually use string.GetEnumerator, but that's the spec'd behavior.
CheckForEachCollectionConvertedType("string", "System.String", "System.String");
// Special case for dynamic
CheckForEachCollectionConvertedType("dynamic", "dynamic", "System.Collections.IEnumerable");
// Pattern-based, not interface-based
CheckForEachCollectionConvertedType("System.Collections.Generic.List<int>", "System.Collections.Generic.List<System.Int32>", "System.Collections.Generic.List<System.Int32>");
// Interface-based
CheckForEachCollectionConvertedType("Enumerable", "Enumerable", "System.Collections.IEnumerable"); // helper method knows definition of this type
// Interface
CheckForEachCollectionConvertedType("System.Collections.Generic.IEnumerable<int>", "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.Generic.IEnumerable<System.Int32>");
// Interface
CheckForEachCollectionConvertedType("NotAType", "NotAType", "NotAType"); // name not in scope
}
private void CheckForEachCollectionConvertedType(string sourceType, string typeDisplayString, string convertedTypeDisplayString)
{
string template = @"
public class Enumerable : System.Collections.IEnumerable
{{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{{
return null;
}}
}}
class Program
{{
void M({0} collection)
{{
foreach (var v in /*<bind>*/collection/*</bind>*/);
}}
}}
";
var semanticInfo = GetSemanticInfoForTest(string.Format(template, sourceType));
Assert.Equal(typeDisplayString, semanticInfo.Type.ToTestDisplayString());
Assert.Equal(convertedTypeDisplayString, semanticInfo.ConvertedType.ToTestDisplayString());
}
[Fact]
public void InaccessibleParameter()
{
string sourceCode = @"
using System;
class Outer
{
class Inner
{
}
}
class Program
{
public static void f(Outer.Inner a) { /*<bind>*/a/*</bind>*/ = 4; }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Outer.Inner", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Outer.Inner", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Outer.Inner a", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
// Parameter's type is an error type, because Outer.Inner is inaccessible.
var param = (IParameterSymbol)semanticInfo.Symbol;
Assert.Equal(TypeKind.Error, param.Type.TypeKind);
// It's type is not equal to the SemanticInfo type, because that is
// not an error type.
Assert.NotEqual(semanticInfo.Type, param.Type);
}
[Fact]
public void StructConstructor()
{
string sourceCode = @"
struct Struct{
public static void Main()
{
Struct s = /*<bind>*/new Struct()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
var symbol = semanticInfo.Symbol;
Assert.NotNull(symbol);
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)symbol).MethodKind);
Assert.True(symbol.IsImplicitlyDeclared);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void MethodGroupAsArgOfInvalidConstructorCall()
{
string sourceCode = @"
using System;
class Class { string M(int i) { new T(/*<bind>*/M/*</bind>*/); } }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.String Class.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.String Class.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void MethodGroupInReturnStatement()
{
string sourceCode = @"
class C
{
public delegate int Func(int i);
public Func Goo()
{
return /*<bind>*/Goo/*</bind>*/;
}
private int Goo(int i)
{
return i;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("C.Func", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C.Goo(int)", semanticInfo.ImplicitConversion.Method.ToString());
Assert.Equal("System.Int32 C.Goo(System.Int32 i)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C.Func C.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.Int32 C.Goo(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateConversionExtensionMethodNoReceiver()
{
string sourceCode =
@"class C
{
static System.Action<object> F()
{
return /*<bind>*/S.E/*</bind>*/;
}
}
static class S
{
internal static void E(this object o) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.NotNull(semanticInfo);
Assert.Equal("System.Action<System.Object>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("void S.E(this System.Object o)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.ImplicitConversion.IsExtensionMethod);
}
[Fact]
public void DelegateConversionExtensionMethod()
{
string sourceCode =
@"class C
{
static System.Action F(object o)
{
return /*<bind>*/o.E/*</bind>*/;
}
}
static class S
{
internal static void E(this object o) { }
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.NotNull(semanticInfo);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal("void System.Object.E()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.IsExtensionMethod);
}
[Fact]
public void InferredVarType()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var x = ""hello"";
/*<bind>*/var/*</bind>*/ y = x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InferredVarTypeWithNamespaceInScope()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
namespace var { }
class Program
{
static void Main(string[] args)
{
var x = ""hello"";
/*<bind>*/var/*</bind>*/ y = x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NonInferredVarType()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
namespace N1
{
class var { }
class Program
{
static void Main(string[] args)
{
/*<bind>*/var/*</bind>*/ x = ""hello"";
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("N1.var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.var", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541207")]
[Fact]
public void UndeclaredVarInThrowExpr()
{
string sourceCode = @"
class Test
{
static void Main()
{
throw /*<bind>*/d1.Get/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo);
}
[Fact]
public void FailedConstructorCall()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C { }
class Program
{
static void Main(string[] args)
{
C c = new /*<bind>*/C/*</bind>*/(17);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void FailedConstructorCall2()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C { }
class Program
{
static void Main(string[] args)
{
C c = /*<bind>*/new C(17)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MemberGroup.Length);
Assert.Equal("C..ctor()", semanticInfo.MemberGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541332")]
[Fact]
public void ImplicitConversionCastExpression()
{
string sourceCode = @"
using System;
enum E { a, b }
class Program
{
static int Main()
{
int ret = /*<bind>*/(int) E.b/*</bind>*/;
return ret - 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToString());
Assert.Equal("int", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541333")]
[Fact]
public void ImplicitConversionAnonymousMethod()
{
string sourceCode = @"
using System;
delegate int D();
class Program
{
static int Main()
{
D d = /*<bind>*/delegate() { return int.MaxValue; }/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<AnonymousMethodExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("D", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
sourceCode = @"
using System;
delegate int D();
class Program
{
static int Main()
{
D d = /*<bind>*/() => { return int.MaxValue; }/*</bind>*/;
return 0;
}
}
";
semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("D", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528476")]
[Fact]
public void BindingInitializerToTargetType()
{
string sourceCode = @"
using System;
class Program
{
static int Main()
{
int[] ret = new int[] /*<bind>*/ { 0, 1, 2 } /*</bind>*/;
return ret[0];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
}
[Fact]
public void BindShortMethodArgument()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void goo(short s)
{
}
static void Main(string[] args)
{
goo(/*<bind>*/123/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(123, semanticInfo.ConstantValue);
}
[WorkItem(541400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541400")]
[Fact]
public void BindingAttributeParameter()
{
string sourceCode = @"
using System;
public class MeAttribute : Attribute
{
public MeAttribute(short p)
{
}
}
[Me(/*<bind>*/123/*</bind>*/)]
public class C
{
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal("int", semanticInfo.Type.ToString());
Assert.Equal("short", semanticInfo.ConvertedType.ToString());
Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BindAttributeFieldNamedArgumentOnMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute
{
public TestAttribute() { }
public string F;
}
class C1
{
[Test(/*<bind>*/F/*</bind>*/=""method"")]
int f() { return 0; }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String TestAttribute.F", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BindAttributePropertyNamedArgumentOnMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute
{
public TestAttribute() { }
public TestAttribute(int i) { }
public string F;
public double P { get; set; }
}
class C1
{
[Test(/*<bind>*/P/*</bind>*/=3.14)]
int f() { return 0; }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Double TestAttribute.P { get; set; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void TestAttributeNamedArgumentValueOnMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute
{
public TestAttribute() { }
public TestAttribute(int i) { }
public string F;
public double P { get; set; }
}
class C1
{
[Test(P=/*<bind>*/1/*</bind>*/)]
int f() { return 0; }
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(540775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540775")]
[Fact]
public void LambdaExprPrecededByAnIncompleteUsingStmt()
{
var code = @"
using System;
class Program
{
static void Main(string[] args)
{
using
Func<int, int> Dele = /*<bind>*/ x => { return x; } /*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(code);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[WorkItem(540785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540785")]
[Fact]
public void NestedLambdaExprPrecededByAnIncompleteNamespaceStmt()
{
var code = @"
using System;
class Program
{
static void Main(string[] args)
{
namespace
Func<int, int> f1 = (x) =>
{
Func<int, int> f2 = /*<bind>*/ (y) => { return y; } /*</bind>*/;
return x;
}
;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(code);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[Fact]
public void DefaultStructConstructor()
{
string sourceCode = @"
using System;
struct Struct{
public static void Main()
{
Struct s = new /*<bind>*/Struct/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Struct", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DefaultStructConstructor2()
{
string sourceCode = @"
using System;
struct Struct{
public static void Main()
{
Struct s = /*<bind>*/new Struct()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Struct..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")]
[Fact]
public void BindAttributeInstanceWithoutAttributeSuffix()
{
string sourceCode = @"
[assembly: /*<bind>*/My/*</bind>*/]
class MyAttribute : System.Attribute { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("MyAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")]
[Fact]
public void BindQualifiedAttributeInstanceWithoutAttributeSuffix()
{
string sourceCode = @"
[assembly: /*<bind>*/N1.My/*</bind>*/]
namespace N1
{
class MyAttribute : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode);
Assert.Equal("N1.MyAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("N1.MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("N1.MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("N1.MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(540770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540770")]
[Fact]
public void IncompleteDelegateCastExpression()
{
string sourceCode = @"
delegate void D();
class MyClass
{
public static int Main()
{
D d;
d = /*<bind>*/(D) delegate /*</bind>*/
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("D", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("D", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(7177, "DevDiv_Projects/Roslyn")]
[Fact]
public void IncompleteGenericDelegateDecl()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
/*<bind>*/Func<int, int> ()/*</bind>*/
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541120")]
[Fact]
public void DelegateCreationArguments()
{
string sourceCode = @"
class Program
{
int goo(int i) { return i;}
static void Main(string[] args)
{
var r = /*<bind>*/new System.Func<int, int>((arg)=> { return 1;}, goo)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateCreationArguments2()
{
string sourceCode = @"
class Program
{
int goo(int i) { return i;}
static void Main(string[] args)
{
var r = new /*<bind>*/System.Func<int, int>/*</bind>*/((arg)=> { return 1;}, goo);
}
}
";
var semanticInfo = GetSemanticInfoForTest<TypeSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void BaseConstructorInitializer2()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: base()/*</bind>*/ { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol).MethodKind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ThisConstructorInitializer2()
{
string sourceCode = @"
class C
{
C() /*<bind>*/: this(1)/*</bind>*/ { }
C(int x) { }
}
";
var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")]
[Fact]
public void TypeInParentOnFieldInitializer()
{
string sourceCode = @"
class MyClass
{
double dbl = /*<bind>*/1/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[Fact]
public void ExplicitIdentityConversion()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int y = 12;
long x = /*<bind>*/(int)y/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541588")]
[Fact]
public void ImplicitConversionElementsInArrayInit()
{
string sourceCode = @"
class MyClass
{
long[] l1 = {/*<bind>*/4L/*</bind>*/, 5L };
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int64", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(4L, semanticInfo.ConstantValue);
}
[WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")]
[Fact]
public void ImplicitConversionArrayInitializer_01()
{
string sourceCode = @"
class MyClass
{
int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")]
[Fact]
public void ImplicitConversionArrayInitializer_02()
{
string sourceCode = @"
class MyClass
{
void Test()
{
int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541595")]
[Fact]
public void ImplicitConversionExprReturnedByLambda()
{
string sourceCode = @"
using System;
class MyClass
{
Func<long> f1 = () => /*<bind>*/4/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.False(semanticInfo.ImplicitConversion.IsIdentity);
Assert.True(semanticInfo.ImplicitConversion.IsImplicit);
Assert.True(semanticInfo.ImplicitConversion.IsNumeric);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(4, semanticInfo.ConstantValue);
}
[WorkItem(541040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541040")]
[WorkItem(528551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528551")]
[Fact]
public void InaccessibleNestedType()
{
string sourceCode = @"
using System;
internal class EClass
{
private enum EEK { a, b, c, d };
}
class Test
{
public void M(EClass.EEK e)
{
b = /*<bind>*/ e /*</bind>*/;
}
EClass.EEK b = EClass.EEK.a;
}
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(SymbolKind.NamedType, semanticInfo.Type.Kind);
Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter1()
{
string sourceCode = @"
using System;
class Program
{
public void f(int x, int y, int z) { }
public void f(string y, string z) { }
public void goo()
{
f(3, /*<bind>*/z/*</bind>*/: 4, y: 9);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 z", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter2()
{
string sourceCode = @"
using System;
class Program
{
public void f(int x, int y, int z) { }
public void f(string y, string z, int q) { }
public void f(string q, int w, int b) { }
public void goo()
{
f(3, /*<bind>*/z/*</bind>*/: ""goo"", y: 9);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 z", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind);
Assert.Equal("System.String z", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter3()
{
string sourceCode = @"
using System;
class Program
{
public void f(int x, int y, int z) { }
public void f(string y, string z, int q) { }
public void f(string q, int w, int b) { }
public void goo()
{
f(3, z: ""goo"", /*<bind>*/yagga/*</bind>*/: 9);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void NamedParameter4()
{
string sourceCode = @"
using System;
namespace ClassLibrary44
{
[MyAttr(/*<bind>*/x/*</bind>*/:1)]
public class Class1
{
}
public class MyAttr: Attribute
{
public MyAttr(int x)
{}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")]
[Fact]
public void ImplicitReferenceConvExtensionMethodReceiver()
{
string sourceCode =
@"public static class Extend
{
public static string TestExt(this object o1)
{
return o1.ToString();
}
}
class Program
{
static void Main(string[] args)
{
string str1 = ""Test"";
var e1 = /*<bind>*/str1/*</bind>*/.TestExt();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.IsReference);
Assert.Equal("System.String str1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
}
[WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")]
[Fact]
public void ImplicitBoxingConvExtensionMethodReceiver()
{
string sourceCode =
@"struct S { }
static class C
{
static void M(S s)
{
/*<bind>*/s/*</bind>*/.F();
}
static void F(this object o)
{
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("S", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.IsBoxing);
Assert.Equal("S s", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind);
}
[Fact]
public void AttributeSyntaxBinding()
{
string sourceCode = @"
using System;
[/*<bind>*/MyAttr(1)/*</bind>*/]
public class Class1
{
}
public class MyAttr: Attribute
{
public MyAttr(int x)
{}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
// Should bind to constructor.
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
}
[WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void MemberAccessOnErrorType()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
string x1 = A./*<bind>*/M/*</bind>*/.C.D.E;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void MemberAccessOnErrorType2()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
string x1 = A./*<bind>*/M/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")]
[Fact]
public void DelegateCreation1()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = new /*<bind>*/MyDelegate/*</bind>*/(this.F);
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = new MyDelegate(MD1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateCreation1_2()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = /*<bind>*/new MyDelegate(this.F)/*</bind>*/;
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = new MyDelegate(MD1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")]
[Fact]
public void DelegateCreation2()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = new MyDelegate(this.F);
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = new /*<bind>*/MyDelegate/*</bind>*/(MD1);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")]
[Fact]
public void DelegateCreation2_2()
{
string sourceCode = @"
class C
{
delegate void MyDelegate();
public void F()
{
MyDelegate MD1 = new MyDelegate(this.F);
MyDelegate MD2 = MD1 + MD1;
MyDelegate MD3 = /*<bind>*/new MyDelegate(MD1)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateSignatureMismatch1()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = new /*<bind>*/Action/*</bind>*/(f);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Action", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateSignatureMismatch2()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = /*<bind>*/new Action(f)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DelegateSignatureMismatch3()
{
// This test and the DelegateSignatureMismatch4 should have identical results, as they are semantically identical
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = new Action(/*<bind>*/f/*</bind>*/);
}
}
";
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Empty(semanticInfo.CandidateSymbols);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
}
[Fact]
public void DelegateSignatureMismatch4()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int f() { return 1; }
static void Main(string[] args)
{
Action a = /*<bind>*/f/*</bind>*/;
}
}
";
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode,
parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Empty(semanticInfo.CandidateSymbols);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
}
[WorkItem(541802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541802")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void IncompleteLetClause()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
/*<bind>*/var/*</bind>*/ q2 = from x in nums
let z = x.
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541895")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void QueryErrorBaseKeywordAsSelectExpression()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new int[] { 1 };
/*<bind>*/var/*</bind>*/ query2 = from int b in expr1 select base;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541805")]
[Fact]
public void InToIdentifierQueryContinuation()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select /*<bind>*/w/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541833")]
[Fact]
public void InOptimizedAwaySelectClause()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
where x > 1
select /*<bind>*/x/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[Fact]
public void InFromClause()
{
string sourceCode = @"
using System;
using System.Linq;
class C
{
void M()
{
int rolf = 732;
int roark = -9;
var replicator = from r in new List<int> { 1, 2, 9, rolf, /*<bind>*/roark/*</bind>*/ } select r * 2;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541911")]
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void QueryErrorGroupJoinFromClause()
{
string sourceCode = @"
class Test
{
static void Main()
{
/*<bind>*/var/*</bind>*/ q =
from Goo i in i
from Goo<int> j in j
group i by i
join Goo
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind);
}
[WorkItem(541920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541920")]
[Fact]
public void SymbolInfoForMissingSelectClauseNode()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string[] strings = { };
var query = from s in strings
let word = s.Split(' ')
from w in w
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var selectClauseNode = tree.FindNodeOrTokenByKind(SyntaxKind.SelectClause).AsNode() as SelectClauseSyntax;
var symbolInfo = semanticModel.GetSymbolInfo(selectClauseNode);
// https://github.com/dotnet/roslyn/issues/38509
// Assert.NotEqual(default, symbolInfo);
Assert.Null(symbolInfo.Symbol);
}
[WorkItem(541940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541940")]
[Fact]
public void IdentifierInSelectNotInContext()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string[] strings = { };
var query = from ch in strings
group ch by ch
into chGroup
where chGroup.Count() >= 2
select /*<bind>*/ x1 /*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
}
[Fact]
public void WhereDefinedInType()
{
var csSource = @"
using System;
class Y
{
public int Where(Func<int, bool> predicate)
{
return 45;
}
}
class P
{
static void Main()
{
var src = new Y();
var query = from x in src
where x > 0
select /*<bind>*/ x /*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(csSource);
Assert.Equal("x", semanticInfo.Symbol.Name);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[WorkItem(541830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541830")]
[Fact]
public void AttributeUsageError()
{
string sourceCode = @"
using System;
[/*<bind>*/AttributeUsage/*</bind>*/()]
class MyAtt : Attribute
{}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
Assert.Equal("AttributeUsageAttribute", semanticInfo.Type.Name);
}
[WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")]
[Fact]
public void OpenGenericTypeInAttribute()
{
string sourceCode = @"
class Gen<T> {}
[/*<bind>*/Gen<T>/*</bind>*/]
public class Test
{
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")]
[Fact]
public void OpenGenericTypeInAttribute02()
{
string sourceCode = @"
class Goo {}
[/*<bind>*/Goo/*</bind>*/]
public class Test
{
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")]
[Fact]
public void IncompleteEmptyAttributeSyntax01()
{
string sourceCode = @"
public class CSEvent {
[
";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax;
var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Symbol);
Assert.Null(semanticInfo.Type);
}
/// <summary>
/// Same as above but with a token after the incomplete
/// attribute so the attribute is not at the end of file.
/// </summary>
[WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")]
[Fact]
public void IncompleteEmptyAttributeSyntax02()
{
string sourceCode = @"
public class CSEvent {
[
}";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.Single();
var semanticModel = compilation.GetSemanticModel(tree);
var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax;
var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode);
Assert.NotNull(semanticInfo);
Assert.Null(semanticInfo.Symbol);
Assert.Null(semanticInfo.Type);
}
[WorkItem(541857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541857")]
[Fact]
public void EventWithInitializerInInterface()
{
string sourceCode = @"
public delegate void MyDelegate();
interface test
{
event MyDelegate e = /*<bind>*/new MyDelegate(Test.Main)/*</bind>*/;
}
class Test
{
static void Main() { }
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("MyDelegate", semanticInfo.Type.ToTestDisplayString());
}
[Fact]
public void SwitchExpression_Constant01()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/true/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
[WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")]
public void SwitchExpression_Constant02()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
const string s = null;
switch (/*<bind>*/s/*</bind>*/)
{
case null:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[Fact]
[WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")]
public void SwitchExpression_NotConstant()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (/*<bind>*/s/*</bind>*/)
{
case null:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState);
Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState);
Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchExpression_Invalid_Lambda()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/()=>3/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Null(semanticInfo.Type);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchExpression_Invalid_MethodGroup()
{
string sourceCode = @"
using System;
public class Test
{
public static int M() {return 0; }
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/M/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Null(semanticInfo.Type);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchExpression_Invalid_GoverningType()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (/*<bind>*/2.2/*</bind>*/)
{
default:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(2.2, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_Null()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
const string s = null;
switch (s)
{
case /*<bind>*/null/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[Fact]
public void SwitchCaseLabelExpression_Constant01()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (true)
{
case /*<bind>*/true/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_Constant02()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
const bool x = true;
switch (true)
{
case /*<bind>*/x/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_NotConstant()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
bool x = true;
switch (true)
{
case /*<bind>*/x/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SwitchCaseLabelExpression_CastExpression()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
switch (ret)
{
case /*<bind>*/(int)'a'/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(97, semanticInfo.ConstantValue);
}
[Fact]
public void SwitchCaseLabelExpression_Invalid_Lambda()
{
string sourceCode = @"
using System;
public class Test
{
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (s)
{
case /*<bind>*/()=>3/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
CreateCompilation(sourceCode).VerifyDiagnostics(
// (12,30): error CS1003: Syntax error, ':' expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(12, 30),
// (12,30): error CS1513: } expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(12, 30),
// (12,44): error CS1002: ; expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(12, 44),
// (12,44): error CS1513: } expected
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(12, 44),
// (12,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(12, 28),
// (12,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type.
// case /*<bind>*/()=>3/*</bind>*/:
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(12, 28)
);
}
[Fact]
public void SwitchCaseLabelExpression_Invalid_LambdaWithSyntaxError()
{
string sourceCode = @"
using System;
public class Test
{
static int M() { return 0;}
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (s)
{
case /*<bind>*/()=>/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
CreateCompilation(sourceCode).VerifyDiagnostics(
// (13,30): error CS1003: Syntax error, ':' expected
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(13, 30),
// (13,30): error CS1513: } expected
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(13, 30),
// (13,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(13, 28),
// (13,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type.
// case /*<bind>*/()=>/*</bind>*/:
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(13, 28)
);
}
[Fact]
public void SwitchCaseLabelExpression_Invalid_MethodGroup()
{
string sourceCode = @"
using System;
public class Test
{
static int M() { return 0;}
public static int Main(string[] args)
{
int ret = 1;
string s = null;
switch (s)
{
case /*<bind>*/M/*</bind>*/:
ret = 0;
break;
}
Console.Write(ret);
return (ret);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541932")]
[Fact]
public void IndexingExpression()
{
string sourceCode = @"
class Test
{
static void Main()
{
string str = ""Test"";
char ch = str[/*<bind>*/ 0 /*</bind>*/];
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(0, semanticInfo.ConstantValue);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
}
[Fact]
public void InaccessibleInTypeof()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
class B { }
}
class Program
{
static void Main(string[] args)
{
object o = typeof(/*<bind>*/A.B/*</bind>*/);
}
}
";
var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode);
Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A.B", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AttributeWithUnboundGenericType01()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/B<>/*</bind>*/))]
class B<T>
{
public class C
{
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.True((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[Fact]
public void AttributeWithUnboundGenericType02()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/B<>.C/*</bind>*/))]
class B<T>
{
public class C
{
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.True((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[Fact]
public void AttributeWithUnboundGenericType03()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/D/*</bind>*/.C<>))]
class B<T>
{
public class C<U>
{
}
}
class D : B<int>
{
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.False((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[Fact]
public void AttributeWithUnboundGenericType04()
{
var sourceCode =
@"using System;
class A : Attribute
{
public A(object o) { }
}
[A(typeof(/*<bind>*/B<>/*</bind>*/.C<>))]
class B<T>
{
public class C<U>
{
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = semanticInfo.Type;
Assert.Equal("B", type.Name);
Assert.True((type as INamedTypeSymbol).IsUnboundGenericType);
Assert.False((type as INamedTypeSymbol).IsErrorType());
}
[WorkItem(542430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542430")]
[Fact]
public void UnboundTypeInvariants()
{
var sourceCode =
@"using System;
public class A<T>
{
int x;
public class B<U>
{
int y;
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(typeof(/*<bind>*/A<>.B<>/*</bind>*/));
}
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = (INamedTypeSymbol)semanticInfo.Type;
Assert.Equal("B", type.Name);
Assert.True(type.IsUnboundGenericType);
Assert.False(type.IsErrorType());
Assert.True(type.TypeArguments[0].IsErrorType());
var constructedFrom = type.ConstructedFrom;
Assert.Equal(constructedFrom, constructedFrom.ConstructedFrom);
Assert.Equal(constructedFrom, constructedFrom.TypeParameters[0].ContainingSymbol);
Assert.Equal(constructedFrom.TypeArguments[0], constructedFrom.TypeParameters[0]);
Assert.Equal(type.ContainingSymbol, constructedFrom.ContainingSymbol);
Assert.Equal(type.TypeParameters[0], constructedFrom.TypeParameters[0]);
Assert.False(constructedFrom.TypeArguments[0].IsErrorType());
Assert.NotEqual(type, constructedFrom);
Assert.False(constructedFrom.IsUnboundGenericType);
var a = type.ContainingType;
Assert.Equal(constructedFrom, a.GetTypeMembers("B").Single());
Assert.NotEqual(type.TypeParameters[0], type.OriginalDefinition.TypeParameters[0]); // alpha renamed
Assert.Null(type.BaseType);
Assert.Empty(type.Interfaces);
Assert.NotNull(constructedFrom.BaseType);
Assert.Empty(type.GetMembers());
Assert.NotEmpty(constructedFrom.GetMembers());
Assert.True(a.IsUnboundGenericType);
Assert.False(a.ConstructedFrom.IsUnboundGenericType);
Assert.Equal(1, a.GetMembers().Length);
}
[WorkItem(528659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528659")]
[Fact]
public void AliasTypeName()
{
string sourceCode = @"
using A = System.String;
class Test
{
static void Main()
{
/*<bind>*/A/*</bind>*/ a = null;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
Assert.Equal("A", aliasInfo.Name);
Assert.Equal("A=System.String", aliasInfo.ToTestDisplayString());
}
[WorkItem(542000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542000")]
[Fact]
public void AmbigAttributeBindWithoutAttributeSuffix()
{
string sourceCode = @"
namespace Blue
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Red
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Green
{
using Blue;
using Red;
public class Test
{
[/*<bind>*/Description/*</bind>*/(null)]
static void Main()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528669")]
[Fact]
public void AmbigAttributeBind1()
{
string sourceCode = @"
namespace Blue
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Red
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace Green
{
using Blue;
using Red;
public class Test
{
[/*<bind>*/DescriptionAttribute/*</bind>*/(null)]
static void Main()
{
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542205")]
[Fact]
public void IncompleteAttributeSymbolInfo()
{
string sourceCode = @"
using System;
class Program
{
[/*<bind>*/ObsoleteAttribute(x/*</bind>*/
static void Main(string[] args)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")]
[Fact]
public void ConstantFieldInitializerExpression()
{
var sourceCode = @"
using System;
public class Aa
{
const int myLength = /*<bind>*/5/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal(5, semanticInfo.ConstantValue);
}
[WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")]
[Fact]
public void CircularConstantFieldInitializerExpression()
{
var sourceCode = @"
public class C
{
const int x = /*<bind>*/x/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542017")]
[Fact]
public void AmbigAttributeBind2()
{
string sourceCode = @"
using System;
[AttributeUsage(AttributeTargets.All)]
public class X : Attribute
{
}
[AttributeUsage(AttributeTargets.All)]
public class XAttribute : Attribute
{
}
[/*<bind>*/X/*</bind>*/]
class Class1
{
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
}
[WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")]
[Fact]
public void AmbigAttributeBind3()
{
string sourceCode = @"
using System;
[AttributeUsage(AttributeTargets.All)]
public class X : Attribute
{
}
[AttributeUsage(AttributeTargets.All)]
public class XAttribute : Attribute
{
}
[/*<bind>*/X/*</bind>*/]
class Class1
{
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
}
[Fact]
public void AmbigAttributeBind4()
{
string sourceCode = @"
namespace ValidWithSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace ValidWithoutSuffix
{
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_01
{
using ValidWithSuffix;
using ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("ValidWithSuffix.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind5()
{
string sourceCode = @"
namespace ValidWithSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace ValidWithSuffix_And_ValidWithoutSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_02
{
using ValidWithSuffix;
using ValidWithSuffix_And_ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.MethodGroup[0].ToDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind6()
{
string sourceCode = @"
namespace ValidWithoutSuffix
{
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace ValidWithSuffix_And_ValidWithoutSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_03
{
using ValidWithoutSuffix;
using ValidWithSuffix_And_ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.MethodGroup[0].ToDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind7()
{
string sourceCode = @"
namespace ValidWithSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
}
namespace ValidWithoutSuffix
{
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace ValidWithSuffix_And_ValidWithoutSuffix
{
public class DescriptionAttribute : System.Attribute
{
public DescriptionAttribute(string name) { }
}
public class Description : System.Attribute
{
public Description(string name) { }
}
}
namespace TestNamespace_04
{
using ValidWithSuffix;
using ValidWithoutSuffix;
using ValidWithSuffix_And_ValidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind8()
{
string sourceCode = @"
namespace InvalidWithSuffix
{
public class DescriptionAttribute
{
public DescriptionAttribute(string name) { }
}
}
namespace InvalidWithoutSuffix
{
public class Description
{
public Description(string name) { }
}
}
namespace TestNamespace_05
{
using InvalidWithSuffix;
using InvalidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AmbigAttributeBind9()
{
string sourceCode = @"
namespace InvalidWithoutSuffix
{
public class Description
{
public Description(string name) { }
}
}
namespace InvalidWithSuffix_And_InvalidWithoutSuffix
{
public class DescriptionAttribute
{
public DescriptionAttribute(string name) { }
}
public class Description
{
public Description(string name) { }
}
}
namespace TestNamespace_07
{
using InvalidWithoutSuffix;
using InvalidWithSuffix_And_InvalidWithoutSuffix;
[/*<bind>*/Description/*</bind>*/(null)]
public class Test { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("InvalidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact()]
public void AliasAttributeName()
{
string sourceCode = @"
using A = A1;
class A1 : System.Attribute { }
[/*<bind>*/A/*</bind>*/] class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("A1", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("A1", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("A1..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A1..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("A=A1", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact()]
public void AliasAttributeName_02_AttributeSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact]
public void AliasAttributeName_02_IdentifierNameSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact]
public void AliasAttributeName_03_AttributeSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact]
public void AliasAttributeName_03_IdentifierNameSyntax()
{
string sourceCode = @"
using GooAttribute = System.ObsoleteAttribute;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.NotNull(aliasInfo);
Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString());
Assert.Equal(SymbolKind.Alias, aliasInfo.Kind);
}
[WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")]
[Fact()]
public void AliasQualifiedAttributeName_01()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[global::/*<bind>*/AttributeClass/*</bind>*/.NonAttributeClass()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()),
"IsAttributeName can be true only for alias name being qualified");
}
[Fact]
public void AliasQualifiedAttributeName_02()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[/*<bind>*/global::AttributeClass/*</bind>*/.NonAttributeClass()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<AliasQualifiedNameSyntax>(sourceCode);
Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()),
"IsAttributeName can be true only for alias name being qualified");
}
[Fact]
public void AliasQualifiedAttributeName_03()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[global::AttributeClass./*<bind>*/NonAttributeClass/*</bind>*/()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AliasQualifiedAttributeName_04()
{
string sourceCode = @"
class AttributeClass : System.Attribute
{
class NonAttributeClass { }
}
namespace N
{
[/*<bind>*/global::AttributeClass.NonAttributeClass/*</bind>*/()]
class C { }
class AttributeClass : System.Attribute { }
}
";
var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AliasAttributeName_NonAttributeAlias()
{
string sourceCode = @"
using GooAttribute = C;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("C", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("C..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AliasAttributeName_NonAttributeAlias_GenericType()
{
string sourceCode = @"
using GooAttribute = Gen<int>;
[/*<bind>*/GooAttribute/*</bind>*/]
class C { }
class Gen<T> { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Gen<System.Int32>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<System.Int32>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<System.Int32>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AmbigAliasAttributeName()
{
string sourceCode = @"
using A = A1;
using AAttribute = A2;
class A1 : System.Attribute { }
class A2 : System.Attribute { }
[/*<bind>*/A/*</bind>*/] class C { }
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("A", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("A1", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("A2", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AmbigAliasAttributeName_02()
{
string sourceCode = @"
using Goo = System.ObsoleteAttribute;
class GooAttribute : System.Attribute { }
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("System.ObsoleteAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[Fact]
public void AmbigAliasAttributeName_03()
{
string sourceCode = @"
using Goo = GooAttribute;
class GooAttribute : System.Attribute { }
[/*<bind>*/Goo/*</bind>*/]
class C { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("GooAttribute", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(aliasInfo);
}
[WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")]
[Fact]
public void AmbigObjectCreationBind()
{
string sourceCode = @"
using System;
public class X
{
}
public struct X
{
}
class Class1
{
public static void Main()
{
object x = new /*<bind>*/X/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal("X", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
}
[WorkItem(542027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542027")]
[Fact()]
public void NonStaticMemberOfOuterTypeAccessedViaNestedType()
{
string sourceCode = @"
class MyClass
{
public int intTest = 1;
class TestClass
{
public void TestMeth()
{
int intI = /*<bind>*/ intTest /*</bind>*/;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass.intTest", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")]
[Fact()]
public void ThisInFieldInitializer()
{
string sourceCode = @"
class MyClass
{
public MyClass self = /*<bind>*/ this /*</bind>*/;
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("MyClass", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MyClass", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal(1, sortedCandidates.Length);
Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")]
[Fact()]
public void BaseInFieldInitializer()
{
string sourceCode = @"
class MyClass
{
public object self = /*<bind>*/ base /*</bind>*/ .Id();
object Id() { return this; }
}";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(SymbolKind.Parameter, semanticInfo.CandidateSymbols[0].Kind);
Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal(1, sortedCandidates.Length);
Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact()]
public void MemberAccessToInaccessibleField()
{
string sourceCode = @"
class MyClass1
{
private static int myInt1 = 12;
}
class MyClass2
{
public int myInt2 = /*<bind>*/MyClass1.myInt1/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass1.myInt1", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528682")]
[Fact]
public void PropertyGetAccessWithPrivateGetter()
{
string sourceCode = @"
public class MyClass
{
public int Property
{
private get { return 0; }
set { }
}
}
public class Test
{
public static void Main(string[] args)
{
MyClass c = new MyClass();
int a = c./*<bind>*/Property/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass.Property { private get; set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")]
[Fact]
public void GetAccessPrivateProperty()
{
string sourceCode = @"
public class Test
{
class Class1
{
private int a { get { return 1; } set { } }
}
class Class2 : Class1
{
public int b() { return /*<bind>*/a/*</bind>*/; }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.Class1.a { get; set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")]
[Fact]
public void GetAccessPrivateField()
{
string sourceCode = @"
public class Test
{
class Class1
{
private int a;
}
class Class2 : Class1
{
public int b() { return /*<bind>*/a/*</bind>*/; }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 Test.Class1.a", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")]
[Fact]
public void GetAccessPrivateEvent()
{
string sourceCode = @"
using System;
public class Test
{
class Class1
{
private event Action a;
}
class Class2 : Class1
{
public Action b() { return /*<bind>*/a/*</bind>*/(); }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind);
Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("event System.Action Test.Class1.a", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Event, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528684")]
[Fact]
public void PropertySetAccessWithPrivateSetter()
{
string sourceCode = @"
public class MyClass
{
public int Property
{
get { return 0; }
private set { }
}
}
public class Test
{
static void Main()
{
MyClass c = new MyClass();
c./*<bind>*/Property/*</bind>*/ = 10;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MyClass.Property { get; private set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void PropertyIndexerAccessWithPrivateSetter()
{
string sourceCode = @"
public class MyClass
{
public object this[int index]
{
get { return null; }
private set { }
}
}
public class Test
{
static void Main()
{
MyClass c = new MyClass();
/*<bind>*/c[0]/*</bind>*/ = null;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Object MyClass.this[System.Int32 index] { get; private set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542065")]
[Fact]
public void GenericTypeWithNoTypeArgsOnAttribute()
{
string sourceCode = @"
class Gen<T> { }
[/*<bind>*/Gen/*</bind>*/]
public class Test
{
public static int Main()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542125")]
[Fact]
public void MalformedSyntaxSemanticModel_Bug9223()
{
string sourceCode = @"
public delegate int D(int x);
public st C
{
public event D EV;
public C(D d)
{
EV = /*<bind>*/d/*</bind>*/;
}
public int OnEV(int x)
{
return x;
}
}
";
// Don't crash or assert.
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
}
[WorkItem(528746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528746")]
[Fact]
public void ImplicitConversionArrayCreationExprInQuery()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q2 = from x in /*<bind>*/new int[] { 4, 5 }/*</bind>*/
select x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542256")]
[Fact]
public void MalformedConditionalExprInWhereClause()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q1 = from x in new int[] { 4, 5 }
where /*<bind>*/new Program()/*</bind>*/ ?
select x;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Symbol);
Assert.Equal("Program..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal("Program", semanticInfo.Type.Name);
}
[WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")]
[Fact]
public void MalformedExpressionInSelectClause()
{
string sourceCode = @"
using System.Linq;
class P
{
static void Main()
{
var src = new int[] { 4, 5 };
var q = from x in src
select /*<bind>*/x/*</bind>*/.";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Symbol);
}
[WorkItem(542344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542344")]
[Fact]
public void LiteralExprInGotoCaseInsideSwitch()
{
string sourceCode = @"
public class Test
{
public static void Main()
{
int ret = 6;
switch (ret)
{
case 0:
goto case /*<bind>*/2/*</bind>*/;
case 2:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType);
Assert.Equal(2, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ImplicitConvCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
long number = 45;
switch (number)
{
case /*<bind>*/21/*</bind>*/:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ErrorConvCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
double number = 45;
switch (number)
{
case /*<bind>*/21/*</bind>*/:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ImplicitConvGotoCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
long number = 45;
switch (number)
{
case 1:
goto case /*<bind>*/21/*</bind>*/;
case 21:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")]
[Fact]
public void ErrorConvGotoCaseConstantExpr()
{
string sourceCode = @"
class Program
{
static void Main()
{
double number = 45;
switch (number)
{
case 1:
goto case /*<bind>*/21/*</bind>*/;
case 21:
break;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(21, semanticInfo.ConstantValue);
}
[WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")]
[Fact]
public void AttributeSemanticInfo_OverloadResolutionFailure_01()
{
string sourceCode = @"
[module: /*<bind>*/System.Obsolete(typeof(.<>))/*</bind>*/]
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo);
}
[WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")]
[Fact]
public void AttributeSemanticInfo_OverloadResolutionFailure_02()
{
string sourceCode = @"
[module: System./*<bind>*/Obsolete/*</bind>*/(typeof(.<>))]
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo);
}
private void Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(CompilationUtils.SemanticInfoSummary semanticInfo)
{
Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(3, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind);
Assert.Equal(3, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString());
Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")]
[Fact]
public void ObjectCreationSemanticInfo_OverloadResolutionFailure()
{
string sourceCode = @"
using System;
class Goo
{
public Goo() { }
public Goo(int x) { }
public static void Main()
{
var x = new /*<bind>*/Goo/*</bind>*/(typeof(.<>));
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Goo", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectCreationSemanticInfo_OverloadResolutionFailure_2()
{
string sourceCode = @"
using System;
class Goo
{
public Goo() { }
public Goo(int x) { }
public static void Main()
{
var x = /*<bind>*/new Goo(typeof(Goo))/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("Goo..ctor(System.Int32 x)", sortedCandidates[1].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.Equal("Goo..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ParameterDefaultValue1()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
void f(long i = 32 + Constants./*<bind>*/k/*</bind>*/, long j = i)
{ }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int16 Constants.k", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal((short)9, semanticInfo.ConstantValue);
}
[Fact]
public void ParameterDefaultValue2()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
void f(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/)
{ }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(12, semanticInfo.ConstantValue);
}
[Fact]
public void ParameterDefaultValueInConstructor()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
Class1(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/)
{ }
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(12, semanticInfo.ConstantValue);
}
[Fact]
public void ParameterDefaultValueInIndexer()
{
string sourceCode = @"
using System;
class Constants
{
public const short k = 9;
}
public class Class1
{
const int i = 12;
const int j = 14;
public string this[long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/]
{
get { return """"; }
set { }
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(12, semanticInfo.ConstantValue);
}
[WorkItem(542589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542589")]
[Fact]
public void UnrecognizedGenericTypeReference()
{
string sourceCode = "/*<bind>*/C<object, string/*</bind>*/";
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode);
var type = (INamedTypeSymbol)semanticInfo.Type;
Assert.Equal("System.Boolean", type.ToTestDisplayString());
}
[WorkItem(542452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542452")]
[Fact]
public void LambdaInSelectExpressionWithObjectCreation()
{
string sourceCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class Test
{
static void Main() { }
static void Goo(List<int> Scores)
{
var z = from y in Scores select new Action(() => { /*<bind>*/var/*</bind>*/ x = y; });
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void DefaultOptionalParamValue()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
const bool v = true;
public void Goo(bool b = /*<bind>*/v == true/*</bind>*/)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode);
Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Boolean System.Boolean.op_Equality(System.Boolean left, System.Boolean right)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(true, semanticInfo.ConstantValue);
}
[Fact]
public void DefaultOptionalParamValueWithGenericTypes()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public void Goo<T, U>(T t = /*<bind>*/default(U)/*</bind>*/) where U : class, T
{
}
static void Main(string[] args)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode);
Assert.Equal("U", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind);
Assert.Equal("T", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.TypeParameter, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Null(semanticInfo.ConstantValue.Value);
}
[WorkItem(542850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542850")]
[Fact]
public void InaccessibleExtensionMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
public static class Extensions
{
private static int Goo(this string z) { return 3; }
}
class Program
{
static void Main(string[] args)
{
args[0]./*<bind>*/Goo/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 System.String.Goo()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 System.String.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542883")]
[Fact]
public void InaccessibleNamedAttrArg()
{
string sourceCode = @"
using System;
public class B : Attribute
{
private int X;
}
[B(/*<bind>*/X/*</bind>*/ = 5)]
public class D { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 B.X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(528914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528914")]
[Fact]
public void InvalidIdentifierAsAttrArg()
{
string sourceCode = @"
using System.Runtime.CompilerServices;
public interface Interface1
{
[/*<bind>*/IndexerName(null)/*</bind>*/]
string this[int arg]
{
get;
set;
}
}
";
var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode);
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.Type.ToTestDisplayString());
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542890")]
[Fact()]
public void GlobalIdentifierName()
{
string sourceCode = @"
class Test
{
static void Main()
{
var t1 = new /*<bind>*/global/*</bind>*/::Test();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.Equal("global", aliasInfo.Name);
Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString());
Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace);
Assert.False(aliasInfo.IsExtern);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact()]
public void GlobalIdentifierName2()
{
string sourceCode = @"
class Test
{
/*<bind>*/global/*</bind>*/::Test f;
static void Main()
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
var aliasInfo = GetAliasInfoForTest(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.Equal("global", aliasInfo.Name);
Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString());
Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace);
Assert.False(aliasInfo.IsExtern);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(542536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542536")]
[Fact]
public void UndeclaredSymbolInDefaultParameterValue()
{
string sourceCode = @"
class Program
{
const int y = 1;
public void Goo(bool x = (undeclared == /*<bind>*/y/*</bind>*/)) { }
static void Main(string[] args)
{
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Program.y", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[WorkItem(543198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543198")]
[Fact]
public void NamespaceAliasInsideMethod()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
using A = NS1;
namespace NS1
{
class B { }
}
class Program
{
class A
{
}
A::B y = null;
void Main()
{
/*<bind>*/A/*</bind>*/::B.Equals(null, null);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
// Should bind to namespace alias A=NS1, not class Program.A.
Assert.Equal("NS1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_ImplicitArrayCreationSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public static int Main()
{
var a = /*<bind>*/new[] { 1, 2, 3 }/*</bind>*/;
return a[0];
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public static int Main()
{
var a = new[] { 1, 2, 3 };
return /*<bind>*/a/*</bind>*/[0];
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32[] a", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_MultiDim_ImplicitArrayCreationSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][, , ] Goo()
{
var a3 = new[] { /*<bind>*/new [,,] {{{1, 2}}}/*</bind>*/, new [,,] {{{3, 4}}} };
return a3;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[,,]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_MultiDim_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][, , ] Goo()
{
var a3 = new[] { new [,,] {{{3, 4}}}, new [,,] {{{3, 4}}} };
return /*<bind>*/a3/*</bind>*/;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32[][,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[][,,]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32[][,,] a3", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_ImplicitArrayCreationSyntax()
{
string sourceCode = @"
public class C
{
public int[] Goo()
{
char c = 'c';
short s1 = 0;
short s2 = -0;
short s3 = 1;
short s4 = -1;
var array1 = /*<bind>*/new[] { s1, s2, s3, s4, c, '1' }/*</bind>*/; // CS0826
return array1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_IdentifierNameSyntax()
{
string sourceCode = @"
public class C
{
public int[] Goo()
{
char c = 'c';
short s1 = 0;
short s2 = -0;
short s3 = 1;
short s4 = -1;
var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826
return /*<bind>*/array1/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("?[] array1", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][,,] Goo()
{
var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, 3, 4 }/*</bind>*/, new[,,] { { { 3, 4 } } } };
return a3;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr_02()
{
string sourceCode = @"
using System;
namespace Test
{
public class Program
{
public int[][,,] Goo()
{
var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, x, y }/*</bind>*/, new[,,] { { { 3, 4 } } } };
return a3;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ImplicitArrayCreationExpression_Inside_ErrorImplicitArrayCreation()
{
string sourceCode = @"
public class C
{
public int[] Goo()
{
char c = 'c';
short s1 = 0;
short s2 = -0;
short s3 = 1;
short s4 = -1;
var array1 = new[] { /*<bind>*/new[] { 1, 2 }/*</bind>*/, new[] { s1, s2, s3, s4, c, '1' } }; // CS0826
return array1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(543201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543201")]
public void BindVariableIncompleteForLoop()
{
string sourceCode = @"
class Program
{
static void Main()
{
for (int i = 0; /*<bind>*/i/*</bind>*/
}
}";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
}
[Fact, WorkItem(542843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542843")]
public void Bug10245()
{
string sourceCode = @"
class C<T> {
public T Field;
}
class D {
void M() {
new C<int>./*<bind>*/Field/*</bind>*/.ToString();
}
}
";
var tree = Parse(sourceCode);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo.CandidateReason);
Assert.Equal(1, symbolInfo.CandidateSymbols.Length);
Assert.Equal("System.Int32 C<System.Int32>.Field", symbolInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Null(symbolInfo.Symbol);
}
[Fact]
public void StaticClassWithinNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/Stat/*</bind>*/();
}
}
static class Stat { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("Stat", semanticInfo.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.CandidateSymbols[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void StaticClassWithinNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new Stat()/*</bind>*/;
}
}
static class Stat { }
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Stat", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("Stat", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543534")]
[Fact]
public void InterfaceWithNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/X/*</bind>*/();
}
}
interface X { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InterfaceWithNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new X()/*</bind>*/;
}
}
interface X { }
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("X", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("X", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void TypeParameterWithNew()
{
string sourceCode = @"
using System;
class Program<T>
{
static void f()
{
object o = new /*<bind>*/T/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("T", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.TypeParameter, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void TypeParameterWithNew2()
{
string sourceCode = @"
using System;
class Program<T>
{
static void f()
{
object o = /*<bind>*/new T()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("T", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("T", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void AbstractClassWithNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/X/*</bind>*/();
}
}
abstract class X { }
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("X", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MemberGroup.Length);
}
[Fact]
public void AbstractClassWithNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new X()/*</bind>*/;
}
}
abstract class X { }
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("X", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MemberGroup.Length);
}
[Fact()]
public void DynamicWithNew()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = new /*<bind>*/dynamic/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("dynamic", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact()]
public void DynamicWithNew2()
{
string sourceCode = @"
using System;
class Program
{
static void Main(string[] args)
{
object o = /*<bind>*/new dynamic()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("dynamic", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind);
Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_01()
{
// There must be exactly one user-defined conversion to a non-nullable integral type,
// and there is.
string sourceCode = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static int Main()
{
Conv C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 1;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitUserDefined, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Conv.implicit operator int(Conv)", semanticInfo.ImplicitConversion.Method.ToString());
Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_02()
{
// The specification requires that the user-defined conversion chosen be one
// which converts to an integral or string type, but *not* a nullable integral type,
// oddly enough. Since the only applicable user-defined conversion here would be the
// lifted conversion from Conv? to int?, the resolution of the conversion fails
// and this program produces an error.
string sourceCode = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static int Main()
{
Conv? C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 1;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Conv?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Conv? C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_01()
{
string sourceCode = @"
struct Conv
{
public static implicit operator int (Conv C)
{
return 1;
}
public static implicit operator int? (Conv? C)
{
return null;
}
public static int Main()
{
Conv C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 0;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_02()
{
string sourceCode = @"
struct Conv
{
public static int Main()
{
Conv C = new Conv();
switch (/*<bind>*/C/*</bind>*/)
{
default:
return 0;
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6);
Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = /*<bind>*/new MemberInitializerTest() { x = 1, y = 2 }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() /*<bind>*/{ x = 1, y = 2 }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_MemberInitializerAssignment_BinaryExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/x = 1/*</bind>*/, y = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_FieldAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/x/*</bind>*/ = 1, y = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_PropertyAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
public static void Main()
{
var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_TypeParameterBaseFieldAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class Base
{
public Base() { }
public int x;
public int y { get; set; }
public static void Main()
{
MemberInitializerTest<Base>.Goo();
}
}
public class MemberInitializerTest<T> where T : Base, new()
{
public static void Goo()
{
var i = new T() { /*<bind>*/x/*</bind>*/ = 1, y = 2 };
System.Console.WriteLine(i.x);
System.Console.WriteLine(i.y);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 Base.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_NestedInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
}
public class Test
{
public readonly MemberInitializerTest m = new MemberInitializerTest();
public static void Main()
{
var i = new Test() { m = /*<bind>*/{ x = 1, y = 2 }/*</bind>*/ };
System.Console.WriteLine(i.m.x);
System.Console.WriteLine(i.m.y);
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_NestedInitializer_PropertyAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
}
public class Test
{
public readonly MemberInitializerTest m = new MemberInitializerTest();
public static void Main()
{
var i = new Test() { m = { x = 1, /*<bind>*/y/*</bind>*/ = 2 } };
System.Console.WriteLine(i.m.x);
System.Console.WriteLine(i.m.y);
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InaccessibleMember_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
protected int x;
private int y { get; set; }
internal int z;
}
public class Test
{
public static void Main()
{
var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2, z = 3 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_ReadOnlyPropertyAssign_IdentifierNameSyntax()
{
string sourceCode = @"
public struct MemberInitializerTest
{
public readonly int x;
public int y { get { return 0; } }
}
public struct Test
{
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/y/*</bind>*/ = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.Int32 MemberInitializerTest.y { get; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_WriteOnlyPropertyAccess_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public int y { get; set; }
}
public class Test
{
public MemberInitializerTest m;
public MemberInitializerTest Prop { set { m = value; } }
public static void Main()
{
var i = new Test() { /*<bind>*/Prop/*</bind>*/ = { x = 1, y = 2 } };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MemberInitializerTest Test.Prop { set; }", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_ErrorInitializerType_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public static void Main()
{
var i = new X() { /*<bind>*/x/*</bind>*/ = 0 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InvalidElementInitializer_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x, y;
public static void Main()
{
var i = new MemberInitializerTest { x = 0, /*<bind>*/y/*</bind>*/++ };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.y", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_InvalidElementInitializer_InvocationExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/};
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_01()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() };
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_02()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public static MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() };
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var symbol = semanticInfo.CandidateSymbols[0];
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, symbol.Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_MethodGroupNamedAssignmentLeft_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
var i = new MemberInitializerTest() { /*<bind>*/Goo/*</bind>*/ };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ObjectInitializer_DuplicateMemberInitializer_IdentifierNameSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int x;
public static void Main()
{
var i = new MemberInitializerTest() { x = 1, /*<bind>*/x/*</bind>*/ = 2 };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = /*<bind>*/new B { 1, i, { 4L }, { 9 }, 3L }/*</bind>*/;
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("B", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("B..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("B..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B /*<bind>*/{ 1, i, { 4L }, { 9 }, 3L }/*</bind>*/;
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ElementInitializer_LiteralExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { /*<bind>*/1/*</bind>*/, i, { 4L }, { 9 }, 3L };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.True(semanticInfo.IsCompileTimeConstant);
Assert.Equal(1, semanticInfo.ConstantValue);
}
[Fact]
public void CollectionInitializer_ElementInitializer_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { 1, /*<bind>*/i/*</bind>*/, { 4L }, { 9 }, 3L };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ComplexElementInitializer_InitializerExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { 1, i, /*<bind>*/{ 4L }/*</bind>*/, { 9 }, 3L };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(long i)
{
list.Add(i);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ComplexElementInitializer_Empty_InitializerExpressionSyntax()
{
string sourceCode = @"
using System.Collections.Generic;
public class MemberInitializerTest
{
public List<int> y;
public static void Main()
{
i = new MemberInitializerTest { y = { /*<bind>*/{ }/*</bind>*/ } }; // CS1920
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_ComplexElementInitializer_AddMethodOverloadResolutionFailure()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var i = 2;
B coll = new B { /*<bind>*/{ 1, 2 }/*</bind>*/ };
DisplayCollection(coll.GetEnumerator());
return 0;
}
public static void DisplayCollection(IEnumerator collection)
{
while (collection.MoveNext())
{
Console.WriteLine(collection.Current);
}
}
}
public class B : IEnumerable
{
List<object> list = new List<object>();
public void Add(float i, int j)
{
list.Add(i);
list.Add(j);
}
public void Add(int i, float j)
{
list.Add(i);
list.Add(j);
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < list.Count; i++)
yield return list[i];
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_Empty_InitializerExpressionSyntax()
{
string sourceCode = @"
using System.Collections.Generic;
public class MemberInitializerTest
{
public static void Main()
{
var i = new List<int>() /*<bind>*/{ }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_Nested_InitializerExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Collections;
class Test
{
public static int Main()
{
var coll = new List<B> { new B(0) { list = new List<int>() { 1, 2, 3 } }, new B(1) { list = /*<bind>*/{ 2, 3 }/*</bind>*/ } };
DisplayCollection(coll);
return 0;
}
public static void DisplayCollection(IEnumerable<B> collection)
{
foreach (var i in collection)
{
i.Display();
}
}
}
public class B
{
public List<int> list = new List<int>();
public B() { }
public B(int i) { list.Add(i); }
public void Display()
{
foreach (var i in list)
{
Console.WriteLine(i);
}
}
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InitializerTypeNotIEnumerable_InitializerExpressionSyntax()
{
string sourceCode = @"
class MemberInitializerTest
{
public static int Main()
{
B coll = new B /*<bind>*/{ 1 }/*</bind>*/;
return 0;
}
}
class B
{
public B() { }
}
";
var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InvalidInitializer_PostfixUnaryExpressionSyntax()
{
string sourceCode = @"
public class MemberInitializerTest
{
public int y;
public static void Main()
{
var i = new MemberInitializerTest { /*<bind>*/y++/*</bind>*/ };
}
}
";
var semanticInfo = GetSemanticInfoForTest<PostfixUnaryExpressionSyntax>(sourceCode);
Assert.Equal("?", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void CollectionInitializer_InvalidInitializer_BinaryExpressionSyntax()
{
string sourceCode = @"
using System.Collections.Generic;
public class MemberInitializerTest
{
public int x;
static MemberInitializerTest Goo() { return new MemberInitializerTest(); }
public static void Main()
{
int y = 0;
var i = new List<int> { 1, /*<bind>*/Goo().x = 1/*</bind>*/};
}
}
";
var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode);
Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SimpleNameWithGenericTypeInAttribute()
{
string sourceCode = @"
class Gen<T> { }
class Gen2<T> : System.Attribute { }
[/*<bind>*/Gen/*</bind>*/]
[Gen2]
public class Test
{
public static int Main()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_SimpleNameWithGenericTypeInAttribute_02()
{
string sourceCode = @"
class Gen<T> { }
class Gen2<T> : System.Attribute { }
[Gen]
[/*<bind>*/Gen2/*</bind>*/]
public class Test
{
public static int Main()
{
return 1;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("Gen2<T>", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("Gen2<T>", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen2<T>..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Gen2<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_VarKeyword_LocalDeclaration()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
/*<bind>*/var/*</bind>*/ rand = new Random();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_VarKeyword_FieldDeclaration()
{
string sourceCode = @"
class Program
{
/*<bind>*/var/*</bind>*/ x = 1;
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_VarKeyword_MethodReturnType()
{
string sourceCode = @"
class Program
{
/*<bind>*/var/*</bind>*/ Goo() {}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("var", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind);
Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")]
[Fact]
public void SemanticInfo_InterfaceCreation_With_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = new /*<bind>*/InterfaceType/*</bind>*/();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")]
[Fact]
public void SemanticInfo_InterfaceArrayCreation_With_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = new /*<bind>*/InterfaceType/*</bind>*/[] { };
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = /*<bind>*/new InterfaceType()/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("CoClassType..ctor()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")]
[Fact]
public void SemanticInfo_InterfaceArrayCreation_With_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
class CoClassType : InterfaceType { }
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
interface InterfaceType { }
public class Program
{
public static void Main()
{
var a = /*<bind>*/new InterfaceType[] { }/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode);
Assert.Equal("InterfaceType[]", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType[]", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class GenericCoClassType<T, U> : NonGenericInterfaceType
{
public GenericCoClassType(U x) { Console.WriteLine(x); }
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(GenericCoClassType<int, string>))]
public interface NonGenericInterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = new /*<bind>*/NonGenericInterfaceType/*</bind>*/(""string"");
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("NonGenericInterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class GenericCoClassType<T, U> : NonGenericInterfaceType
{
public GenericCoClassType(U x) { Console.WriteLine(x); }
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(GenericCoClassType<int, string>))]
public interface NonGenericInterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = /*<bind>*/new NonGenericInterfaceType(""string"")/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("NonGenericInterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("NonGenericInterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_IdentifierNameSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class Wrapper
{
private class CoClassType : InterfaceType
{
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
public interface InterfaceType
{
}
}
public class MainClass
{
public static int Main()
{
var a = new Wrapper./*<bind>*/InterfaceType/*</bind>*/();
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("Wrapper.InterfaceType", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
public class Wrapper
{
private class CoClassType : InterfaceType
{
}
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(CoClassType))]
public interface InterfaceType
{
}
}
public class MainClass
{
public static int Main()
{
var a = /*<bind>*/new Wrapper.InterfaceType()/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("Wrapper.InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("Wrapper.InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("Wrapper.CoClassType..ctor()", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
Assert.Equal("Wrapper.CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(int))]
public interface InterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = /*<bind>*/new InterfaceType()/*</bind>*/;
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("InterfaceType", semanticInfo.CandidateSymbols.First().Name);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax_2()
{
string sourceCode = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")]
[CoClass(typeof(int))]
public interface InterfaceType
{
}
public class MainClass
{
public static int Main()
{
var a = new /*<bind>*/InterfaceType/*</bind>*/();
return 0;
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("InterfaceType", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(543593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543593")]
[Fact]
public void IncompletePropertyAccessStatement()
{
string sourceCode =
@"class C
{
static void M()
{
var c = new { P = 0 };
/*<bind>*/c.P.Q/*</bind>*/ x;
}
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Symbol);
}
[WorkItem(544449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544449")]
[Fact]
public void IndexerAccessorWithSyntaxErrors()
{
string sourceCode =
@"public abstract int this[int i]
(
{
/*<bind>*/get/*</bind>*/;
set;
}";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Null(semanticInfo.Symbol);
}
[WorkItem(545040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545040")]
[Fact]
public void OmittedArraySizeExpressionSyntax()
{
string sourceCode =
@"
class A
{
public static void Main()
{
var arr = new int[5][
];
}
}
";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.First();
var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedArraySizeExpressionSyntax>().Last();
var model = compilation.GetSemanticModel(tree);
var typeInfo = model.GetTypeInfo(node); // Ensure that this doesn't throw.
Assert.NotEqual(default, typeInfo);
}
[WorkItem(11451, "DevDiv_Projects/Roslyn")]
[Fact]
public void InvalidNewInterface()
{
string sourceCode = @"
using System;
public class Program
{
static void Main(string[] args)
{
var c = new /*<bind>*/IFormattable/*</bind>*/
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("System.IFormattable", sortedCandidates[0].ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void InvalidNewInterface2()
{
string sourceCode = @"
using System;
public class Program
{
static void Main(string[] args)
{
var c = /*<bind>*/new IFormattable()/*</bind>*/
}
}
";
var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode);
Assert.Equal("System.IFormattable", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind);
Assert.Equal("System.IFormattable", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason);
Assert.Equal(1, semanticInfo.CandidateSymbols.Length);
Assert.Equal("System.IFormattable", semanticInfo.CandidateSymbols.First().ToTestDisplayString());
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(545376, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545376")]
[Fact]
public void AssignExprInExternEvent()
{
string sourceCode = @"
struct Class1
{
public event EventHandler e2;
extern public event EventHandler e1 = /*<bind>*/ e2 = new EventHandler(this, new EventArgs()) = null /*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode);
Assert.NotNull(semanticInfo.Type);
}
[Fact, WorkItem(531416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531416")]
public void VarEvent()
{
var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(@"
event /*<bind>*/var/*</bind>*/ goo;
");
Assert.True(((ITypeSymbol)semanticInfo.Type).IsErrorType());
}
[WorkItem(546083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546083")]
[Fact]
public void GenericMethodAssignedToDelegateWithDeclErrors()
{
string sourceCode = @"
delegate void D(void t);
class C {
void M<T>(T t) {
}
D d = /*<bind>*/M/*</bind>*/;
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Utils.CheckSymbol(semanticInfo.CandidateSymbols.Single(), "void C.M<T>(T t)");
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Null(semanticInfo.Type);
Utils.CheckSymbol(semanticInfo.ConvertedType, "D");
}
[WorkItem(545992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545992")]
[Fact]
public void TestSemanticInfoForMembersOfCyclicBase()
{
string sourceCode = @"
using System;
using System.Collections;
class B : C
{
}
class C : B
{
static void Main()
{
}
void Goo(int x)
{
/*<bind>*/(this).Goo(1)/*</bind>*/;
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("void C.Goo(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(610975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610975")]
[Fact]
public void AttributeOnTypeParameterWithSameName()
{
string source = @"
class C<[T(a: 1)]T>
{
}
";
var comp = CreateCompilation(source);
comp.GetParseDiagnostics().Verify(); // Syntactically correct.
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var argumentSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single();
var argumentNameSyntax = argumentSyntax.NameColon.Name;
var info = model.GetSymbolInfo(argumentNameSyntax);
}
private void CommonTestParenthesizedMethodGroup(string sourceCode)
{
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal("void C.Goo()", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(1, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("void C.Goo()", sortedMethodGroup[0].ToTestDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
[WorkItem(576966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576966")]
public void TestParenthesizedMethodGroup()
{
string sourceCode = @"
class C
{
void Goo()
{
/*<bind>*/Goo/*</bind>*/();
}
}";
CommonTestParenthesizedMethodGroup(sourceCode);
sourceCode = @"
class C
{
void Goo()
{
((/*<bind>*/Goo/*</bind>*/))();
}
}";
CommonTestParenthesizedMethodGroup(sourceCode);
}
[WorkItem(531549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531549")]
[Fact()]
public void Bug531549()
{
var sourceCode1 = @"
class C1
{
void Goo()
{
int x = 2;
long? z = /*<bind>*/x/*</bind>*/;
}
}";
var sourceCode2 = @"
class C2
{
void Goo()
{
long? y = /*<bind>*/x/*</bind>*/;
int x = 2;
}
}";
var compilation = CreateCompilation(new[] { sourceCode1, sourceCode2 });
for (int i = 0; i < 2; i++)
{
var tree = compilation.SyntaxTrees[i];
var model = compilation.GetSemanticModel(tree);
IdentifierNameSyntax syntaxToBind = GetSyntaxNodeOfTypeForBinding<IdentifierNameSyntax>(GetSyntaxNodeList(tree));
var info1 = model.GetTypeInfo(syntaxToBind);
Assert.NotEqual(default, info1);
Assert.Equal("System.Int32", info1.Type.ToTestDisplayString());
}
}
[Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")]
public void ObjectCreation1()
{
var compilation = CreateCompilation(
@"
using System.Collections;
namespace Test
{
class C : IEnumerable
{
public int P1 { get; set; }
public void Add(int x)
{ }
public static void Main()
{
var x1 = new C();
var x2 = new C() {P1 = 1};
var x3 = new C() {1, 2};
}
public static void Main2()
{
var x1 = new Test.C();
var x2 = new Test.C() {P1 = 1};
var x3 = new Test.C() {1, 2};
}
public IEnumerator GetEnumerator()
{
return null;
}
}
}");
compilation.VerifyDiagnostics();
SyntaxTree tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as ObjectCreationExpressionSyntax)).
Where(node => (object)node != null).ToArray();
for (int i = 0; i < 6; i++)
{
ObjectCreationExpressionSyntax creation = nodes[i];
SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type);
Assert.Equal("Test.C", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var memberGroup = model.GetMemberGroup(creation.Type);
Assert.Equal(0, memberGroup.Length);
TypeInfo typeInfo = model.GetTypeInfo(creation.Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
var conv = model.GetConversion(creation.Type);
Assert.True(conv.IsIdentity);
symbolInfo = model.GetSymbolInfo(creation);
Assert.Equal("Test.C..ctor()", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
memberGroup = model.GetMemberGroup(creation);
Assert.Equal(1, memberGroup.Length);
Assert.Equal("Test.C..ctor()", memberGroup[0].ToTestDisplayString());
typeInfo = model.GetTypeInfo(creation);
Assert.Equal("Test.C", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Test.C", typeInfo.ConvertedType.ToTestDisplayString());
conv = model.GetConversion(creation);
Assert.True(conv.IsIdentity);
}
}
[Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")]
public void ObjectCreation2()
{
var compilation = CreateCompilation(
@"
using System.Collections;
namespace Test
{
public class CoClassI : I
{
public int P1 { get; set; }
public void Add(int x)
{ }
public IEnumerator GetEnumerator()
{
return null;
}
}
[System.Runtime.InteropServices.ComImport, System.Runtime.InteropServices.CoClass(typeof(CoClassI))]
[System.Runtime.InteropServices.Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public interface I : IEnumerable
{
int P1 { get; set; }
void Add(int x);
}
class C
{
public static void Main()
{
var x1 = new I();
var x2 = new I() {P1 = 1};
var x3 = new I() {1, 2};
}
public static void Main2()
{
var x1 = new Test.I();
var x2 = new Test.I() {P1 = 1};
var x3 = new Test.I() {1, 2};
}
}
}
");
compilation.VerifyDiagnostics();
SyntaxTree tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as ObjectCreationExpressionSyntax)).
Where(node => (object)node != null).ToArray();
for (int i = 0; i < 6; i++)
{
ObjectCreationExpressionSyntax creation = nodes[i];
SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type);
Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var memberGroup = model.GetMemberGroup(creation.Type);
Assert.Equal(0, memberGroup.Length);
TypeInfo typeInfo = model.GetTypeInfo(creation.Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
var conv = model.GetConversion(creation.Type);
Assert.True(conv.IsIdentity);
symbolInfo = model.GetSymbolInfo(creation);
Assert.Equal("Test.CoClassI..ctor()", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
memberGroup = model.GetMemberGroup(creation);
Assert.Equal(1, memberGroup.Length);
Assert.Equal("Test.CoClassI..ctor()", memberGroup[0].ToTestDisplayString());
typeInfo = model.GetTypeInfo(creation);
Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString());
conv = model.GetConversion(creation);
Assert.True(conv.IsIdentity);
}
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")]
public void ObjectCreation3()
{
var pia = CreateCompilation(
@"
using System;
using System.Collections;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
namespace Test
{
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b5827A"")]
public class CoClassI : I
{
public int P1 { get; set; }
public void Add(int x)
{ }
public IEnumerator GetEnumerator()
{
return null;
}
}
[ComImport()]
[Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")]
[System.Runtime.InteropServices.CoClass(typeof(CoClassI))]
public interface I : IEnumerable
{
int P1 { get; set; }
void Add(int x);
}
}
", options: TestOptions.ReleaseDll);
pia.VerifyDiagnostics();
var compilation = CreateCompilation(
@"
namespace Test
{
class C
{
public static void Main()
{
var x1 = new I();
var x2 = new I() {P1 = 1};
var x3 = new I() {1, 2};
}
public static void Main2()
{
var x1 = new Test.I();
var x2 = new Test.I() {P1 = 1};
var x3 = new Test.I() {1, 2};
}
}
}", references: new[] { new CSharpCompilationReference(pia, embedInteropTypes: true) });
compilation.VerifyDiagnostics();
SyntaxTree tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var nodes = (from node in tree.GetRoot().DescendantNodes()
select (node as ObjectCreationExpressionSyntax)).
Where(node => (object)node != null).ToArray();
for (int i = 0; i < 6; i++)
{
ObjectCreationExpressionSyntax creation = nodes[i];
SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type);
Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
var memberGroup = model.GetMemberGroup(creation.Type);
Assert.Equal(0, memberGroup.Length);
TypeInfo typeInfo = model.GetTypeInfo(creation.Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
var conv = model.GetConversion(creation.Type);
Assert.True(conv.IsIdentity);
symbolInfo = model.GetSymbolInfo(creation);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
memberGroup = model.GetMemberGroup(creation);
Assert.Equal(0, memberGroup.Length);
typeInfo = model.GetTypeInfo(creation);
Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString());
Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString());
conv = model.GetConversion(creation);
Assert.True(conv.IsIdentity);
}
}
/// <summary>
/// SymbolInfo and TypeInfo should implement IEquatable<T>.
/// </summary>
[WorkItem(792647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792647")]
[Fact]
public void ImplementsIEquatable()
{
string sourceCode =
@"class C
{
object F()
{
return this;
}
}";
var compilation = CreateCompilation(sourceCode);
var tree = compilation.SyntaxTrees.First();
var expr = (ExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ThisKeyword).Parent;
var model = compilation.GetSemanticModel(tree);
var symbolInfo1 = model.GetSymbolInfo(expr);
var symbolInfo2 = model.GetSymbolInfo(expr);
var symbolComparer = (IEquatable<SymbolInfo>)symbolInfo1;
Assert.True(symbolComparer.Equals(symbolInfo2));
var typeInfo1 = model.GetTypeInfo(expr);
var typeInfo2 = model.GetTypeInfo(expr);
var typeComparer = (IEquatable<TypeInfo>)typeInfo1;
Assert.True(typeComparer.Equals(typeInfo2));
}
[Fact]
public void ConditionalAccessErr001()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = """"qqq"""" ?/*<bind>*/.ToString().Length/*</bind>*/.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccessErr002()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = ""qqq"" ?/*<bind>*/.ToString/*</bind>*/.Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<MemberBindingExpressionSyntax>(sourceCode);
Assert.Null(semanticInfo.Type);
Assert.Null(semanticInfo.ConvertedType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
var sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("string.ToString()", sortedCandidates[0].ToDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
Assert.Equal("string.ToString(System.IFormatProvider)", sortedCandidates[1].ToDisplayString());
Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);
Assert.Equal(2, semanticInfo.MethodGroup.Length);
var sortedMethodGroup = semanticInfo.MethodGroup.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray();
Assert.Equal("string.ToString()", sortedMethodGroup[0].ToDisplayString());
Assert.Equal("string.ToString(System.IFormatProvider)", sortedMethodGroup[1].ToDisplayString());
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess001()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = ""qqq"" ?/*<bind>*/.ToString()/*</bind>*/.Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode);
Assert.Equal("string", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("string", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.ToString()", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess002()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString().Length ?.ToString();
var dummy2 = ""qqq"" ?.ToString()./*<bind>*/Length/*</bind>*/.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess003()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null)?.ToString()./*<bind>*/Length/*</bind>*/?.ToString();
var dummy2 = ""qqq""?.ToString().Length.ToString();
var dummy3 = 1.ToString()?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("?", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess004()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString()./*<bind>*/Length/*</bind>*/ .ToString();
var dummy2 = ""qqq"" ?.ToString().Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("int", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact]
public void ConditionalAccess005()
{
string sourceCode = @"
public class C
{
static void Main()
{
var dummy1 = ((string)null) ?.ToString() ?/*<bind>*/[1]/*</bind>*/ .ToString();
var dummy2 = ""qqq"" ?.ToString().Length.ToString();
var dummy3 = 1.ToString() ?.ToString().Length.ToString();
}
}
";
var semanticInfo = GetSemanticInfoForTest<ElementBindingExpressionSyntax>(sourceCode);
Assert.Equal("char", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind);
Assert.Equal("char", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("string.this[int]", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(998050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998050")]
public void Bug998050()
{
var comp = CreateCompilation(@"
class BaselineLog
{}
public static BaselineLog Log
{
get
{
}
}= new /*<bind>*/BaselineLog/*</bind>*/();
", parseOptions: TestOptions.Regular);
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(comp);
Assert.Null(semanticInfo.Type);
Assert.Equal("BaselineLog", semanticInfo.Symbol.ToDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(982479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/982479")]
public void Bug982479()
{
const string sourceCode = @"
class C
{
static void Main()
{
new C { Dynamic = { /*<bind>*/Name/*</bind>*/ = 1 } };
}
public dynamic Dynamic;
}
class Name
{
}
";
var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode);
Assert.Equal("dynamic", semanticInfo.Type.ToDisplayString());
Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind);
Assert.Equal("dynamic", semanticInfo.ConvertedType.ToDisplayString());
Assert.Equal(TypeKind.Dynamic, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Null(semanticInfo.Symbol);
Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[Fact, WorkItem(1084693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084693")]
public void Bug1084693()
{
const string sourceCode =
@"
using System;
public class C {
public Func<Func<C, C>, C> Select;
public Func<Func<C, bool>, C> Where => null;
public void M() {
var e =
from i in this
where true
select true?i:i;
}
}";
var compilation = CreateCompilation(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
string[] expectedNames = { null, "Where", "Select" };
int i = 0;
foreach (var qc in tree.GetRoot().DescendantNodes().OfType<QueryClauseSyntax>())
{
var infoSymbol = semanticModel.GetQueryClauseInfo(qc).OperationInfo.Symbol;
Assert.Equal(expectedNames[i++], infoSymbol?.Name);
}
var qe = tree.GetRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Single();
var infoSymbol2 = semanticModel.GetSymbolInfo(qe.Body.SelectOrGroup).Symbol;
Assert.Equal(expectedNames[i++], infoSymbol2.Name);
}
[Fact]
public void TestIncompleteMember()
{
// Note: binding information in an incomplete member is not available.
// When https://github.com/dotnet/roslyn/issues/7536 is fixed this test
// will have to be updated.
string sourceCode = @"
using System;
class Program
{
public /*<bind>*/K/*</bind>*/
}
class K
{ }
";
var semanticInfo = GetSemanticInfoForTest(sourceCode);
Assert.Equal("K", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind);
Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
Assert.Equal("K", semanticInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind);
Assert.Equal(0, semanticInfo.CandidateSymbols.Length);
Assert.Equal(0, semanticInfo.MethodGroup.Length);
Assert.False(semanticInfo.IsCompileTimeConstant);
}
[WorkItem(18763, "https://github.com/dotnet/roslyn/issues/18763")]
[Fact]
public void AttributeArgumentLambdaThis()
{
string source =
@"class C
{
[X(() => this._Y)]
public void Z()
{
}
}";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.ThisExpression);
var info = model.GetSemanticInfoSummary(syntax);
Assert.Equal("C", info.Type.Name);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/ExtensionManager/IInfoBarService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Extensions
{
internal interface IInfoBarService : IWorkspaceService
{
/// <summary>
/// Show global info bar
/// </summary>
void ShowInfoBar(string message, params InfoBarUI[] items);
}
internal struct InfoBarUI
{
public readonly string? Title;
public readonly UIKind Kind;
public readonly Action Action;
public readonly bool CloseAfterAction;
public InfoBarUI(string title, UIKind kind, Action action, bool closeAfterAction = true)
{
Contract.ThrowIfNull(title);
Title = title;
Kind = kind;
Action = action;
CloseAfterAction = closeAfterAction;
}
[MemberNotNullWhen(false, nameof(Title))]
public bool IsDefault => Title == null;
internal enum UIKind
{
Button,
HyperLink,
Close
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Extensions
{
internal interface IInfoBarService : IWorkspaceService
{
/// <summary>
/// Show global info bar
/// </summary>
void ShowInfoBar(string message, params InfoBarUI[] items);
}
internal struct InfoBarUI
{
public readonly string? Title;
public readonly UIKind Kind;
public readonly Action Action;
public readonly bool CloseAfterAction;
public InfoBarUI(string title, UIKind kind, Action action, bool closeAfterAction = true)
{
Contract.ThrowIfNull(title);
Title = title;
Kind = kind;
Action = action;
CloseAfterAction = closeAfterAction;
}
[MemberNotNullWhen(false, nameof(Title))]
public bool IsDefault => Title == null;
internal enum UIKind
{
Button,
HyperLink,
Close
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/EditorConfigSettings/Common/IEnumSettingViewModelFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal interface IEnumSettingViewModelFactory
{
bool IsSupported(OptionKey2 key);
IEnumSettingViewModel CreateViewModel(FormattingSetting setting);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal interface IEnumSettingViewModelFactory
{
bool IsSupported(OptionKey2 key);
IEnumSettingViewModel CreateViewModel(FormattingSetting setting);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/CodeLens/LocationComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeLens
{
internal sealed class LocationComparer : IEqualityComparer<Location>
{
public static LocationComparer Instance { get; } = new LocationComparer();
public bool Equals(Location x, Location y)
{
if (x != null && x.IsInSource && y != null && y.IsInSource)
{
return x.SourceSpan.Equals(y.SourceSpan) &&
x.SourceTree.FilePath.Equals(y.SourceTree.FilePath, StringComparison.OrdinalIgnoreCase);
}
return object.Equals(x, y);
}
public int GetHashCode(Location obj)
{
if (obj != null && obj.IsInSource)
{
return Hash.Combine(obj.SourceSpan.GetHashCode(),
StringComparer.OrdinalIgnoreCase.GetHashCode(obj.SourceTree.FilePath));
}
return obj?.GetHashCode() ?? 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeLens
{
internal sealed class LocationComparer : IEqualityComparer<Location>
{
public static LocationComparer Instance { get; } = new LocationComparer();
public bool Equals(Location x, Location y)
{
if (x != null && x.IsInSource && y != null && y.IsInSource)
{
return x.SourceSpan.Equals(y.SourceSpan) &&
x.SourceTree.FilePath.Equals(y.SourceTree.FilePath, StringComparison.OrdinalIgnoreCase);
}
return object.Equals(x, y);
}
public int GetHashCode(Location obj)
{
if (obj != null && obj.IsInSource)
{
return Hash.Combine(obj.SourceSpan.GetHashCode(),
StringComparer.OrdinalIgnoreCase.GetHashCode(obj.SourceTree.FilePath));
}
return obj?.GetHashCode() ?? 0;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/OverloadResolutionResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
#if DEBUG
using System.Text;
#endif
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Summarizes the results of an overload resolution analysis, as described in section 7.5 of
/// the language specification. Describes whether overload resolution succeeded, and which
/// method was selected if overload resolution succeeded, as well as detailed information about
/// each method that was considered.
/// </summary>
internal class OverloadResolutionResult<TMember> where TMember : Symbol
{
private MemberResolutionResult<TMember> _bestResult;
private ThreeState _bestResultState;
internal readonly ArrayBuilder<MemberResolutionResult<TMember>> ResultsBuilder;
// Create an overload resolution result from a single result.
internal OverloadResolutionResult()
{
this.ResultsBuilder = new ArrayBuilder<MemberResolutionResult<TMember>>();
}
internal void Clear()
{
_bestResult = default(MemberResolutionResult<TMember>);
_bestResultState = ThreeState.Unknown;
this.ResultsBuilder.Clear();
}
/// <summary>
/// True if overload resolution successfully selected a single best method.
/// </summary>
public bool Succeeded
{
get
{
EnsureBestResultLoaded();
return _bestResultState == ThreeState.True && _bestResult.Result.IsValid;
}
}
/// <summary>
/// If overload resolution successfully selected a single best method, returns information
/// about that method. Otherwise returns null.
/// </summary>
public MemberResolutionResult<TMember> ValidResult
{
get
{
EnsureBestResultLoaded();
Debug.Assert(_bestResultState == ThreeState.True && _bestResult.Result.IsValid);
return _bestResult;
}
}
private void EnsureBestResultLoaded()
{
if (!_bestResultState.HasValue())
{
_bestResultState = TryGetBestResult(this.ResultsBuilder, out _bestResult);
}
}
/// <summary>
/// If there was a method that overload resolution considered better than all others,
/// returns information about that method. A method may be returned even if that method was
/// not considered a successful overload resolution, as long as it was better that any other
/// potential method considered.
/// </summary>
public MemberResolutionResult<TMember> BestResult
{
get
{
EnsureBestResultLoaded();
Debug.Assert(_bestResultState == ThreeState.True);
return _bestResult;
}
}
/// <summary>
/// Returns information about each method that was considered during overload resolution,
/// and what the results of overload resolution were for that method.
/// </summary>
public ImmutableArray<MemberResolutionResult<TMember>> Results
{
get
{
return this.ResultsBuilder.ToImmutable();
}
}
/// <summary>
/// Returns true if one or more of the members in the group are applicable. (Note that
/// Succeeded implies IsApplicable but IsApplicable does not imply Succeeded. It is possible
/// that no applicable member was better than all others.)
/// </summary>
internal bool HasAnyApplicableMember
{
get
{
foreach (var res in this.ResultsBuilder)
{
if (res.Result.IsApplicable)
{
return true;
}
}
return false;
}
}
/// <summary>
/// Returns all methods in the group that are applicable, <see cref="HasAnyApplicableMember"/>.
/// </summary>
internal ImmutableArray<TMember> GetAllApplicableMembers()
{
var result = ArrayBuilder<TMember>.GetInstance();
foreach (var res in this.ResultsBuilder)
{
if (res.Result.IsApplicable)
{
result.Add(res.Member);
}
}
return result.ToImmutableAndFree();
}
private static ThreeState TryGetBestResult(ArrayBuilder<MemberResolutionResult<TMember>> allResults, out MemberResolutionResult<TMember> best)
{
best = default(MemberResolutionResult<TMember>);
ThreeState haveBest = ThreeState.False;
foreach (var pair in allResults)
{
if (pair.Result.IsValid)
{
if (haveBest == ThreeState.True)
{
Debug.Assert(false, "How did we manage to get two methods in the overload resolution results that were both better than every other method?");
best = default(MemberResolutionResult<TMember>);
return ThreeState.False;
}
haveBest = ThreeState.True;
best = pair;
}
}
// TODO: There might be a situation in which there were no valid results but we still want to identify a "best of a bad lot" result for
// TODO: error reporting.
return haveBest;
}
/// <summary>
/// Called when overload resolution has failed. Figures out the best way to describe what went wrong.
/// </summary>
/// <remarks>
/// Overload resolution (effectively) starts out assuming that all candidates are valid and then
/// gradually disqualifies them. Therefore, our strategy will be to perform our checks in the
/// reverse order - the farther a candidate got through the process without being flagged, the
/// "better" it was.
///
/// Note that "final validation" is performed after overload resolution,
/// so final validation errors are not seen here. Final validation errors include
/// violations of constraints on method type parameters, static/instance mismatches,
/// and so on.
/// </remarks>
internal void ReportDiagnostics<T>(
Binder binder,
Location location,
SyntaxNode nodeOpt,
BindingDiagnosticBag diagnostics,
string name,
BoundExpression receiver,
SyntaxNode invokedExpression,
AnalyzedArguments arguments,
ImmutableArray<T> memberGroup, // the T is just a convenience for the caller
NamedTypeSymbol typeContainingConstructor,
NamedTypeSymbol delegateTypeBeingInvoked,
CSharpSyntaxNode queryClause = null,
bool isMethodGroupConversion = false,
RefKind? returnRefKind = null,
TypeSymbol delegateOrFunctionPointerType = null) where T : Symbol
{
Debug.Assert(!this.Succeeded, "Don't ask for diagnostic info on a successful overload resolution result.");
// Each argument must have non-null Display in case it is used in a diagnostic.
Debug.Assert(arguments.Arguments.All(a => a.Display != null));
// This kind is only used for default(MemberResolutionResult<T>), so we should never see it in
// the candidate list.
AssertNone(MemberResolutionKind.None);
var symbols = StaticCast<Symbol>.From(memberGroup);
//// PHASE 1: Valid candidates ////
// Since we're here, we know that there isn't exactly one applicable candidate. There may,
// however, be more than one. We'll check for that first, since applicable candidates are
// always better than inapplicable candidates.
if (HadAmbiguousBestMethods(diagnostics, symbols, location))
{
return;
}
// Since we didn't return, we know that there aren't two or more applicable candidates.
// From above, we know there isn't exactly one either. Therefore, there must not be any
// applicable candidates.
AssertNone(MemberResolutionKind.ApplicableInNormalForm);
AssertNone(MemberResolutionKind.ApplicableInExpandedForm);
// There are two ways that otherwise-applicable candidates can be ruled out by overload resolution:
// a) there is another applicable candidate that is strictly better, or
// b) there is another applicable candidate from a more derived type.
// There can't be exactly one such candidate, since that would the existence of some better
// applicable candidate, which would have either won or been detected above. It is possible,
// however, that there are multiple candidates that are worse than each other in a cycle.
// This might sound like a paradox, but it is in fact possible. Because there are
// intransitivities in convertibility (where A-->B, B-->C and C-->A but none of the
// opposite conversions are legal) there are also intransitivities in betterness.
// (Obviously, there can't be a LessDerived cycle, since we break type hierarchy cycles during
// symbol table construction.)
if (HadAmbiguousWorseMethods(diagnostics, symbols, location, queryClause != null, receiver, name))
{
return;
}
// Since we didn't return, we know that there aren't two or "worse" candidates. As above,
// there also can't be a single one. Therefore, there are none.
AssertNone(MemberResolutionKind.Worse);
// If there's a less-derived candidate, it must be less derived than some applicable or
// "worse" candidate. Since there are none of those, there must not be any less-derived
// candidates either.
AssertNone(MemberResolutionKind.LessDerived);
//// PHASE 2: Applicability failures ////
// Overload resolution performed these checks just before weeding out less-derived and worse candidates.
// If we got as far as converting a lambda to a delegate type, and we failed to
// do so, then odds are extremely good that the failure is the ultimate cause
// of the overload resolution failing to find any applicable method. Report
// the errors out of each lambda argument, if there were any.
// NOTE: There isn't a MemberResolutionKind for this error condition.
if (HadLambdaConversionError(diagnostics, arguments))
{
return;
}
// If there is any instance(or alternatively static) method accessed through a
// type(or alternatively expression) then the first such method is the best bad method.
// To retain existing behavior, we use the location of the invoked expression for the error.
if (HadStaticInstanceMismatch(diagnostics, symbols, invokedExpression?.GetLocation() ?? location, binder, receiver, nodeOpt, delegateOrFunctionPointerType))
{
return;
}
// When overload resolution is being done to resolve a method group conversion (to a delegate type),
// if there is any method being converted to a delegate type, but the method's return
// ref kind does not match the delegate, then the first such method is the best bad method.
// Otherwise if there is any method whose return type does not match the delegate, then the
// first such method is the best bad method
if (isMethodGroupConversion && returnRefKind != null &&
HadReturnMismatch(location, diagnostics, returnRefKind.GetValueOrDefault(), delegateOrFunctionPointerType))
{
return;
}
// Otherwise, if there is any such method where type inference succeeded but inferred
// type arguments that violate the constraints on the method, then the first such method is
// the best bad method.
if (HadConstraintFailure(location, diagnostics))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.ConstraintFailure);
// Otherwise, if there is any such method that has a bad argument conversion or out/ref mismatch
// then the first such method found is the best bad method.
if (HadBadArguments(diagnostics, binder, name, arguments, symbols, location, binder.Flags, isMethodGroupConversion))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.BadArgumentConversion);
// Otherwise, if there is any such method where type inference succeeded but inferred
// a parameter type that violates its own constraints then the first such method is
// the best bad method.
if (HadConstructedParameterFailedConstraintCheck(binder.Conversions, binder.Compilation, diagnostics, location))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.ConstructedParameterFailedConstraintCheck);
// Otherwise, if there is any such method where type inference succeeded but inferred
// an inaccessible type then the first such method found is the best bad method.
if (InaccessibleTypeArgument(diagnostics, symbols, location))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.InaccessibleTypeArgument);
// Otherwise, if there is any such method where type inference failed then the
// first such method is the best bad method.
if (TypeInferenceFailed(binder, diagnostics, symbols, receiver, arguments, location, queryClause))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.TypeInferenceFailed);
AssertNone(MemberResolutionKind.TypeInferenceExtensionInstanceArgument);
//// PHASE 3: Use site errors ////
// Overload resolution checks for use site errors between argument analysis and applicability testing.
// Otherwise, if there is any such method that cannot be used because it is
// in an unreferenced assembly then the first such method is the best bad method.
if (UseSiteError())
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.UseSiteError);
//// PHASE 4: Argument analysis failures and unsupported metadata ////
// The first to checks in overload resolution are for unsupported metadata (Symbol.HasUnsupportedMetadata)
// and argument analysis. We don't want to report unsupported metadata unless nothing else went wrong -
// otherwise we'd report errors about losing candidates, effectively "pulling in" unnecessary assemblies.
bool supportedRequiredParameterMissingConflicts = false;
MemberResolutionResult<TMember> firstSupported = default(MemberResolutionResult<TMember>);
MemberResolutionResult<TMember> firstUnsupported = default(MemberResolutionResult<TMember>);
var supportedInPriorityOrder = new MemberResolutionResult<TMember>[7]; // from highest to lowest priority
const int duplicateNamedArgumentPriority = 0;
const int requiredParameterMissingPriority = 1;
const int nameUsedForPositionalPriority = 2;
const int noCorrespondingNamedParameterPriority = 3;
const int noCorrespondingParameterPriority = 4;
const int badNonTrailingNamedArgumentPriority = 5;
const int wrongCallingConventionPriority = 6;
foreach (MemberResolutionResult<TMember> result in this.ResultsBuilder)
{
switch (result.Result.Kind)
{
case MemberResolutionKind.UnsupportedMetadata:
if (firstSupported.IsNull)
{
firstUnsupported = result;
}
break;
case MemberResolutionKind.NoCorrespondingNamedParameter:
if (supportedInPriorityOrder[noCorrespondingNamedParameterPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[noCorrespondingNamedParameterPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[noCorrespondingNamedParameterPriority] = result;
}
break;
case MemberResolutionKind.NoCorrespondingParameter:
if (supportedInPriorityOrder[noCorrespondingParameterPriority].IsNull)
{
supportedInPriorityOrder[noCorrespondingParameterPriority] = result;
}
break;
case MemberResolutionKind.RequiredParameterMissing:
if (supportedInPriorityOrder[requiredParameterMissingPriority].IsNull)
{
Debug.Assert(!supportedRequiredParameterMissingConflicts);
supportedInPriorityOrder[requiredParameterMissingPriority] = result;
}
else
{
supportedRequiredParameterMissingConflicts = true;
}
break;
case MemberResolutionKind.NameUsedForPositional:
if (supportedInPriorityOrder[nameUsedForPositionalPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[nameUsedForPositionalPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[nameUsedForPositionalPriority] = result;
}
break;
case MemberResolutionKind.BadNonTrailingNamedArgument:
if (supportedInPriorityOrder[badNonTrailingNamedArgumentPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[badNonTrailingNamedArgumentPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[badNonTrailingNamedArgumentPriority] = result;
}
break;
case MemberResolutionKind.DuplicateNamedArgument:
{
if (supportedInPriorityOrder[duplicateNamedArgumentPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[duplicateNamedArgumentPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[duplicateNamedArgumentPriority] = result;
}
}
break;
case MemberResolutionKind.WrongCallingConvention:
{
if (supportedInPriorityOrder[wrongCallingConventionPriority].IsNull)
{
supportedInPriorityOrder[wrongCallingConventionPriority] = result;
}
}
break;
default:
// Based on the asserts above, we know that only the kinds above
// are possible at this point. This should only throw if a new
// kind is added without appropriate checking above.
throw ExceptionUtilities.UnexpectedValue(result.Result.Kind);
}
}
foreach (var supported in supportedInPriorityOrder)
{
if (supported.IsNotNull)
{
firstSupported = supported;
break;
}
}
// If there are any supported candidates, we don't care about unsupported candidates.
if (firstSupported.IsNotNull)
{
if (firstSupported.Member is FunctionPointerMethodSymbol
&& firstSupported.Result.Kind == MemberResolutionKind.NoCorrespondingNamedParameter)
{
int badArg = firstSupported.Result.BadArgumentsOpt[0];
Debug.Assert(arguments.Names[badArg].HasValue);
Location badName = arguments.Names[badArg].GetValueOrDefault().Location;
diagnostics.Add(ErrorCode.ERR_FunctionPointersCannotBeCalledWithNamedArguments, badName);
return;
}
// If there are multiple supported candidates, we don't have a good way to choose the best
// one so we report a general diagnostic (below).
else if (!(firstSupported.Result.Kind == MemberResolutionKind.RequiredParameterMissing && supportedRequiredParameterMissingConflicts)
&& !isMethodGroupConversion
// Function pointer type symbols don't have named parameters, so we just want to report a general mismatched parameter
// count instead of name errors.
&& (firstSupported.Member is not FunctionPointerMethodSymbol))
{
switch (firstSupported.Result.Kind)
{
// Otherwise, if there is any such method that has a named argument and a positional
// argument for the same parameter then the first such method is the best bad method.
case MemberResolutionKind.NameUsedForPositional:
ReportNameUsedForPositional(firstSupported, diagnostics, arguments, symbols);
return;
// Otherwise, if there is any such method that has a named argument that corresponds
// to no parameter then the first such method is the best bad method.
case MemberResolutionKind.NoCorrespondingNamedParameter:
ReportNoCorrespondingNamedParameter(firstSupported, name, diagnostics, arguments, delegateTypeBeingInvoked, symbols);
return;
// Otherwise, if there is any such method that has a required parameter
// but no argument was supplied for it then the first such method is
// the best bad method.
case MemberResolutionKind.RequiredParameterMissing:
// CONSIDER: for consistency with dev12, we would goto default except in omitted ref cases.
ReportMissingRequiredParameter(firstSupported, diagnostics, delegateTypeBeingInvoked, symbols, location);
return;
// NOTE: For some reason, there is no specific handling for this result kind.
case MemberResolutionKind.NoCorrespondingParameter:
break;
// Otherwise, if there is any such method that has a named argument was used out-of-position
// and followed by unnamed arguments.
case MemberResolutionKind.BadNonTrailingNamedArgument:
ReportBadNonTrailingNamedArgument(firstSupported, diagnostics, arguments, symbols);
return;
case MemberResolutionKind.DuplicateNamedArgument:
ReportDuplicateNamedArgument(firstSupported, diagnostics, arguments);
return;
}
}
else if (firstSupported.Result.Kind == MemberResolutionKind.WrongCallingConvention)
{
ReportWrongCallingConvention(location, diagnostics, symbols, firstSupported, ((FunctionPointerTypeSymbol)delegateOrFunctionPointerType).Signature);
return;
}
}
else if (firstUnsupported.IsNotNull)
{
// Otherwise, if there is any such method that cannot be used because it is
// unsupported by the language then the first such method is the best bad method.
// This is the first kind of problem overload resolution checks for, so it should
// be the last MemberResolutionKind we check for. Candidates with this kind
// failed the soonest.
// CONSIDER: report his on every unsupported candidate?
ReportUnsupportedMetadata(location, diagnostics, symbols, firstUnsupported);
return;
}
// If the user provided a number of arguments that works for no possible method in the method
// group then we give an error saying that. Every method will have an error of the form
// "missing required parameter" or "argument corresponds to no parameter", and therefore we
// have no way of choosing a "best bad method" to report the error on. We should simply
// say that no possible method can take the given number of arguments.
// CAVEAT: For method group conversions, the caller reports a different diagnostics.
if (!isMethodGroupConversion)
{
ReportBadParameterCount(diagnostics, name, arguments, symbols, location, typeContainingConstructor, delegateTypeBeingInvoked);
}
}
private static void ReportUnsupportedMetadata(Location location, BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, MemberResolutionResult<TMember> firstUnsupported)
{
DiagnosticInfo diagInfo = firstUnsupported.Member.GetUseSiteInfo().DiagnosticInfo;
Debug.Assert(diagInfo != null);
Debug.Assert(diagInfo.Severity == DiagnosticSeverity.Error);
// Attach symbols to the diagnostic info.
diagInfo = new DiagnosticInfoWithSymbols(
(ErrorCode)diagInfo.Code,
diagInfo.Arguments,
symbols);
Symbol.ReportUseSiteDiagnostic(diagInfo, diagnostics, location);
}
private static void ReportWrongCallingConvention(Location location, BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, MemberResolutionResult<TMember> firstSupported, MethodSymbol target)
{
Debug.Assert(firstSupported.Result.Kind == MemberResolutionKind.WrongCallingConvention);
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_WrongFuncPtrCallingConvention,
new object[] { firstSupported.Member, target.CallingConvention },
symbols), location);
}
private bool UseSiteError()
{
var bad = GetFirstMemberKind(MemberResolutionKind.UseSiteError);
if (bad.IsNull)
{
return false;
}
Debug.Assert(bad.Member.GetUseSiteInfo().DiagnosticInfo.Severity == DiagnosticSeverity.Error,
"Why did we use MemberResolutionKind.UseSiteError if we didn't have a use site error?");
// Use site errors are reported unconditionally in PerformMemberOverloadResolution/PerformObjectCreationOverloadResolution.
return true;
}
private bool InaccessibleTypeArgument(
BindingDiagnosticBag diagnostics,
ImmutableArray<Symbol> symbols,
Location location)
{
var inaccessible = GetFirstMemberKind(MemberResolutionKind.InaccessibleTypeArgument);
if (inaccessible.IsNull)
{
return false;
}
// error CS0122: 'M<X>(I<X>)' is inaccessible due to its protection level
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_BadAccess,
new object[] { inaccessible.Member },
symbols), location);
return true;
}
private bool HadStaticInstanceMismatch(
BindingDiagnosticBag diagnostics,
ImmutableArray<Symbol> symbols,
Location location,
Binder binder,
BoundExpression receiverOpt,
SyntaxNode nodeOpt,
TypeSymbol delegateOrFunctionPointerType)
{
var staticInstanceMismatch = GetFirstMemberKind(MemberResolutionKind.StaticInstanceMismatch);
if (staticInstanceMismatch.IsNull)
{
return false;
}
Symbol symbol = staticInstanceMismatch.Member;
// Certain compiler-generated invocations produce custom diagnostics.
if (receiverOpt?.Kind == BoundKind.QueryClause)
{
// Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found.
diagnostics.Add(ErrorCode.ERR_QueryNoProvider, location, receiverOpt.Type, symbol.Name);
}
else if (binder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod))
{
diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, location, symbol);
}
else if (nodeOpt?.Kind() == SyntaxKind.AwaitExpression && symbol.Name == WellKnownMemberNames.GetAwaiter)
{
diagnostics.Add(ErrorCode.ERR_BadAwaitArg, location, receiverOpt.Type);
}
else if (delegateOrFunctionPointerType is FunctionPointerTypeSymbol)
{
diagnostics.Add(ErrorCode.ERR_FuncPtrMethMustBeStatic, location, symbol);
}
else
{
ErrorCode errorCode =
symbol.RequiresInstanceReceiver()
? Binder.WasImplicitReceiver(receiverOpt) && binder.InFieldInitializer && !binder.BindingTopLevelScriptCode
? ErrorCode.ERR_FieldInitRefNonstatic
: ErrorCode.ERR_ObjectRequired
: ErrorCode.ERR_ObjectProhibited;
// error CS0176: Member 'Program.M(B)' cannot be accessed with an instance reference; qualify it with a type name instead
// -or-
// error CS0120: An object reference is required for the non-static field, method, or property 'Program.M(B)'
diagnostics.Add(new DiagnosticInfoWithSymbols(
errorCode,
new object[] { symbol },
symbols), location);
}
return true;
}
private bool HadReturnMismatch(Location location, BindingDiagnosticBag diagnostics, RefKind refKind, TypeSymbol delegateOrFunctionPointerType)
{
var mismatch = GetFirstMemberKind(MemberResolutionKind.WrongRefKind);
if (!mismatch.IsNull)
{
diagnostics.Add(delegateOrFunctionPointerType.IsFunctionPointer() ? ErrorCode.ERR_FuncPtrRefMismatch : ErrorCode.ERR_DelegateRefMismatch,
location, mismatch.Member, delegateOrFunctionPointerType);
return true;
}
mismatch = GetFirstMemberKind(MemberResolutionKind.WrongReturnType);
if (!mismatch.IsNull)
{
var method = (MethodSymbol)(Symbol)mismatch.Member;
diagnostics.Add(ErrorCode.ERR_BadRetType, location, method, method.ReturnType);
return true;
}
return false;
}
private bool HadConstraintFailure(Location location, BindingDiagnosticBag diagnostics)
{
var constraintFailure = GetFirstMemberKind(MemberResolutionKind.ConstraintFailure);
if (constraintFailure.IsNull)
{
return false;
}
foreach (var pair in constraintFailure.Result.ConstraintFailureDiagnostics)
{
if (pair.UseSiteInfo.DiagnosticInfo is object)
{
diagnostics.Add(new CSDiagnostic(pair.UseSiteInfo.DiagnosticInfo, location));
}
}
return true;
}
private bool TypeInferenceFailed(
Binder binder,
BindingDiagnosticBag diagnostics,
ImmutableArray<Symbol> symbols,
BoundExpression receiver,
AnalyzedArguments arguments,
Location location,
CSharpSyntaxNode queryClause = null)
{
var inferenceFailed = GetFirstMemberKind(MemberResolutionKind.TypeInferenceFailed);
if (inferenceFailed.IsNotNull)
{
if (queryClause != null)
{
Binder.ReportQueryInferenceFailed(queryClause, inferenceFailed.Member.Name, receiver, arguments, symbols, diagnostics);
}
else
{
// error CS0411: The type arguments for method 'M<T>(T)' cannot be inferred
// from the usage. Try specifying the type arguments explicitly.
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_CantInferMethTypeArgs,
new object[] { inferenceFailed.Member },
symbols), location);
}
return true;
}
inferenceFailed = GetFirstMemberKind(MemberResolutionKind.TypeInferenceExtensionInstanceArgument);
if (inferenceFailed.IsNotNull)
{
Debug.Assert(arguments.Arguments.Count > 0);
var instanceArgument = arguments.Arguments[0];
if (queryClause != null)
{
binder.ReportQueryLookupFailed(queryClause, instanceArgument, inferenceFailed.Member.Name, symbols, diagnostics);
}
else
{
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_NoSuchMemberOrExtension,
new object[] { instanceArgument.Type, inferenceFailed.Member.Name },
symbols), location);
}
return true;
}
return false;
}
private static void ReportNameUsedForPositional(
MemberResolutionResult<TMember> bad,
BindingDiagnosticBag diagnostics,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols)
{
int badArg = bad.Result.BadArgumentsOpt[0];
// We would not have gotten this error had there not been a named argument.
Debug.Assert(arguments.Names.Count > badArg);
Debug.Assert(arguments.Names[badArg].HasValue);
(string badName, Location location) = arguments.Names[badArg].GetValueOrDefault();
Debug.Assert(badName != null);
// Named argument 'x' specifies a parameter for which a positional argument has already been given
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_NamedArgumentUsedInPositional,
new object[] { badName },
symbols), location);
}
private static void ReportBadNonTrailingNamedArgument(
MemberResolutionResult<TMember> bad,
BindingDiagnosticBag diagnostics,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols)
{
int badArg = bad.Result.BadArgumentsOpt[0];
// We would not have gotten this error had there not been a named argument.
Debug.Assert(arguments.Names.Count > badArg);
Debug.Assert(arguments.Names[badArg].HasValue);
(string badName, Location location) = arguments.Names[badArg].GetValueOrDefault();
Debug.Assert(badName != null);
// Named argument 'x' is used out-of-position but is followed by an unnamed argument.
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_BadNonTrailingNamedArgument,
new object[] { badName },
symbols), location);
}
private static void ReportDuplicateNamedArgument(MemberResolutionResult<TMember> result, BindingDiagnosticBag diagnostics, AnalyzedArguments arguments)
{
Debug.Assert(result.Result.BadArgumentsOpt.Length == 1);
Debug.Assert(arguments.Names[result.Result.BadArgumentsOpt[0]].HasValue);
(string name, Location location) = arguments.Names[result.Result.BadArgumentsOpt[0]].GetValueOrDefault();
Debug.Assert(name != null);
// CS: Named argument '{0}' cannot be specified multiple times
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_DuplicateNamedArgument, name), location);
}
private static void ReportNoCorrespondingNamedParameter(
MemberResolutionResult<TMember> bad,
string methodName,
BindingDiagnosticBag diagnostics,
AnalyzedArguments arguments,
NamedTypeSymbol delegateTypeBeingInvoked,
ImmutableArray<Symbol> symbols)
{
// We know that there is at least one method that had a number of arguments
// passed that was valid for *some* method in the candidate set. Given that
// fact, we seek the *best* method in the candidate set to report the error
// on. If we have a method that has a valid number of arguments, but the
// call was inapplicable because there was a bad name, that's a candidate
// for the "best" overload.
int badArg = bad.Result.BadArgumentsOpt[0];
// We would not have gotten this error had there not been a named argument.
Debug.Assert(arguments.Names.Count > badArg);
Debug.Assert(arguments.Names[badArg].HasValue);
(string badName, Location location) = arguments.Names[badArg].GetValueOrDefault();
Debug.Assert(badName != null);
// error CS1739: The best overload for 'M' does not have a parameter named 'x'
// Error CS1746: The delegate 'D' does not have a parameter named 'x'
ErrorCode code = (object)delegateTypeBeingInvoked != null ?
ErrorCode.ERR_BadNamedArgumentForDelegateInvoke :
ErrorCode.ERR_BadNamedArgument;
object obj = (object)delegateTypeBeingInvoked ?? methodName;
diagnostics.Add(new DiagnosticInfoWithSymbols(
code,
new object[] { obj, badName },
symbols), location);
}
private static void ReportMissingRequiredParameter(
MemberResolutionResult<TMember> bad,
BindingDiagnosticBag diagnostics,
NamedTypeSymbol delegateTypeBeingInvoked,
ImmutableArray<Symbol> symbols,
Location location)
{
// We know that there is at least one method that had a number of arguments
// passed that was valid for *some* method in the candidate set. Given that
// fact, we seek the *best* method in the candidate set to report the error
// on. If we have a method that has a valid number of arguments, but the
// call was inapplicable because a required parameter does not have a
// corresponding argument then that's a candidate for the "best" overload.
//
// For example, you might have M(int x, int y, int z = 3) and a call
// M(1, z:4) -- the error cannot be "no overload of M takes 2 arguments"
// because M does take two arguments; M(1, 2) would be legal. The
// error instead has to be that there was no argument corresponding
// to required formal parameter 'y'.
TMember badMember = bad.Member;
ImmutableArray<ParameterSymbol> parameters = badMember.GetParameters();
int badParamIndex = bad.Result.BadParameter;
string badParamName;
if (badParamIndex == parameters.Length)
{
Debug.Assert(badMember.Kind == SymbolKind.Method);
Debug.Assert(((MethodSymbol)(object)badMember).IsVararg);
badParamName = SyntaxFacts.GetText(SyntaxKind.ArgListKeyword);
}
else
{
badParamName = parameters[badParamIndex].Name;
}
// There is no argument given that corresponds to the required formal parameter '{0}' of '{1}'
object obj = (object)delegateTypeBeingInvoked ?? badMember;
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_NoCorrespondingArgument,
new object[] { badParamName, obj },
symbols), location);
}
private static void ReportBadParameterCount(
BindingDiagnosticBag diagnostics,
string name,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols,
Location location,
NamedTypeSymbol typeContainingConstructor,
NamedTypeSymbol delegateTypeBeingInvoked)
{
// error CS1501: No overload for method 'M' takes n arguments
// error CS1729: 'M' does not contain a constructor that takes n arguments
// error CS1593: Delegate 'M' does not take n arguments
// error CS8757: Function pointer 'M' does not take n arguments
FunctionPointerMethodSymbol functionPointerMethodBeingInvoked = symbols.IsDefault || symbols.Length != 1
? null
: symbols[0] as FunctionPointerMethodSymbol;
(ErrorCode code, object target) = (typeContainingConstructor, delegateTypeBeingInvoked, functionPointerMethodBeingInvoked) switch
{
(object t, _, _) => (ErrorCode.ERR_BadCtorArgCount, t),
(_, object t, _) => (ErrorCode.ERR_BadDelArgCount, t),
(_, _, object t) => (ErrorCode.ERR_BadFuncPointerArgCount, t),
_ => (ErrorCode.ERR_BadArgCount, name)
};
int argCount = arguments.Arguments.Count;
if (arguments.IsExtensionMethodInvocation)
{
argCount--;
}
diagnostics.Add(new DiagnosticInfoWithSymbols(
code,
new object[] { target, argCount },
symbols), location);
return;
}
private bool HadConstructedParameterFailedConstraintCheck(
ConversionsBase conversions,
CSharpCompilation compilation,
BindingDiagnosticBag diagnostics,
Location location)
{
// We know that there is at least one method that had a number of arguments
// passed that was valid for *some* method in the candidate set. Given that
// fact, we seek the *best* method in the candidate set to report the error
// on. If we have a generic method that has a valid number of arguments, but the
// call was inapplicable because a formal parameter type failed to meet its
// constraints, give an error.
//
// That could happen like this:
//
// void Q<T>(T t1, Nullable<T> t2) where T : struct
//
// Q("", null);
//
// Every required parameter has a corresponding argument. Type inference succeeds and infers
// that T is string. Each argument is convertible to the corresponding formal parameter type.
// What makes this a not-applicable candidate is not that the constraint on T is violated, but
// rather that the constraint on *Nullable<T>* is violated; Nullable<string> is not a legal
// type, and so this is not an applicable candidate.
//
// In language versions before the feature 'ImprovedOverloadCandidates' was added to the language,
// checking whether constraints are violated *on T in Q<T>* occurs *after* overload resolution
// successfully chooses a unique best method; but with the addition of the
// feature 'ImprovedOverloadCandidates', constraint checks on the method's own type arguments
// occurs during candidate selection.
//
// Note that this failure need not involve type inference; Q<string>(null, null) would also be
// illegal for the same reason.
//
// The question then arises as to what error to report here. The native compiler reports that
// the constraint is violated on the method, even though the fact that precipitates the
// failure of overload resolution to classify this as an applicable candidate is the constraint
// violation on Nullable<T>. Most of the time this is actually a pretty sensible error message;
// if you say Q<string>(...) then it seems reasonable to give an error that says that string is
// bad for Q, not that it is bad for its formal parameters under construction. Since the compiler
// will not allow Q<T> to be declared without a constraint that ensures that Nullable<T>'s
// constraints are met, typically a failure to provide a type argument that works for the
// formal parameter type will also be a failure for the method type parameter.
//
// However, there could be error recovery scenarios. Suppose instead we had said
//
// void Q<T>(T t1, Nullable<T> t2)
//
// with no constraint on T. We will give an error at declaration time, but if later we
// are asked to provide an analysis of Q<string>("", null), the right thing to do is NOT
// to say "constraint is violated on T in Q<T>" because there is no constraint to be
// violated here. The error is (1) that the constraint is violated on Nullable<T> and
// (2) that there is a constraint missing on Q<T>.
//
// Another error-recovery scenario in which the method's constraint is not violated:
//
// struct C<U> where U : struct {}
// ...
// void Q<T>(Nullable<T> nt) where T : struct {}
// ...
// Q<C<string>>(null);
//
// C<string> is clearly an error, but equally clearly it does not violate the constraint
// on T because it is a struct. If we attempt overload resolution then overload resolution
// will say that Q<C<string>> is not an applicable candidate because N<C<string>> is not
// a valid type. N is not the problem; C<string> is a struct. C<string> is the problem.
//
// See test case CS0310ERR_NewConstraintNotSatisfied02 for an even more complex version
// of this flavor of error recovery.
var result = GetFirstMemberKind(MemberResolutionKind.ConstructedParameterFailedConstraintCheck);
if (result.IsNull)
{
return false;
}
// We would not have gotten as far as type inference succeeding if the argument count
// was invalid.
// Normally a failure to meet constraints on a formal parameter type is also a failure
// to meet constraints on the method's type argument. See if that's the case; if it
// is, then just report that error.
MethodSymbol method = (MethodSymbol)(Symbol)result.Member;
if (!method.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, location, diagnostics)))
{
// The error is already reported into the diagnostics bag.
return true;
}
// We are in the unusual position that a constraint has been violated on a formal parameter type
// without being violated on the method. Report that the constraint is violated on the
// formal parameter type.
TypeSymbol formalParameterType = method.GetParameterType(result.Result.BadParameter);
formalParameterType.CheckAllConstraints(new ConstraintsHelper.CheckConstraintsArgsBoxed((CSharpCompilation)compilation, conversions, includeNullability: false, location, diagnostics));
return true;
}
private static bool HadLambdaConversionError(BindingDiagnosticBag diagnostics, AnalyzedArguments arguments)
{
bool hadError = false;
foreach (var argument in arguments.Arguments)
{
if (argument.Kind == BoundKind.UnboundLambda)
{
hadError |= ((UnboundLambda)argument).GenerateSummaryErrors(diagnostics);
}
}
return hadError;
}
private bool HadBadArguments(
BindingDiagnosticBag diagnostics,
Binder binder,
string name,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols,
Location location,
BinderFlags flags,
bool isMethodGroupConversion)
{
var badArg = GetFirstMemberKind(MemberResolutionKind.BadArgumentConversion);
if (badArg.IsNull)
{
return false;
}
if (isMethodGroupConversion)
{
return true;
}
var method = badArg.Member;
// The best overloaded method match for '{0}' has some invalid arguments
// Since we have bad arguments to report, there is no need to report an error on the invocation itself.
//var di = new DiagnosticInfoWithSymbols(
// ErrorCode.ERR_BadArgTypes,
// new object[] { badArg.Method },
// symbols);
//
if (flags.Includes(BinderFlags.CollectionInitializerAddMethod))
{
// However, if we are binding the collection initializer Add method, we do want to generate
// ErrorCode.ERR_BadArgTypesForCollectionAdd or ErrorCode.ERR_InitializerAddHasParamModifiers
// as there is no explicit call to Add method.
foreach (var parameter in method.GetParameters())
{
if (parameter.RefKind != RefKind.None)
{
// The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
diagnostics.Add(ErrorCode.ERR_InitializerAddHasParamModifiers, location, symbols, method);
return true;
}
}
// The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
diagnostics.Add(ErrorCode.ERR_BadArgTypesForCollectionAdd, location, symbols, method);
}
foreach (var arg in badArg.Result.BadArgumentsOpt)
{
ReportBadArgumentError(diagnostics, binder, name, arguments, symbols, location, badArg, method, arg);
}
return true;
}
private static void ReportBadArgumentError(
BindingDiagnosticBag diagnostics,
Binder binder,
string name,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols,
Location location,
MemberResolutionResult<TMember> badArg,
TMember method,
int arg)
{
BoundExpression argument = arguments.Argument(arg);
if (argument.HasAnyErrors)
{
// If the argument had an error reported then do not report further errors for
// overload resolution failure.
return;
}
int parm = badArg.Result.ParameterFromArgument(arg);
SourceLocation sourceLocation = new SourceLocation(argument.Syntax);
// Early out: if the bad argument is an __arglist parameter then simply report that:
if (method.GetIsVararg() && parm == method.GetParameterCount())
{
// NOTE: No SymbolDistinguisher required, since one of the arguments is "__arglist".
// CS1503: Argument {0}: cannot convert from '{1}' to '{2}'
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
argument.Display,
"__arglist");
return;
}
ParameterSymbol parameter = method.GetParameters()[parm];
bool isLastParameter = method.GetParameterCount() == parm + 1; // This is used to later decide if we need to try to unwrap a params array
RefKind refArg = arguments.RefKind(arg);
RefKind refParameter = parameter.RefKind;
if (arguments.IsExtensionMethodThisArgument(arg))
{
Debug.Assert(refArg == RefKind.None);
if (refParameter == RefKind.Ref || refParameter == RefKind.In)
{
// For ref and ref-readonly extension methods, we omit the "ref" modifier on receiver arguments.
// Setting the correct RefKind for finding the correct diagnostics message.
// For other ref kinds, keeping it as it is to find mismatch errors.
refArg = refParameter;
}
}
// If the expression is untyped because it is a lambda, anonymous method, method group or null
// then we never want to report the error "you need a ref on that thing". Rather, we want to
// say that you can't convert "null" to "ref int".
if (!argument.HasExpressionType() &&
argument.Kind != BoundKind.OutDeconstructVarPendingInference &&
argument.Kind != BoundKind.OutVariablePendingInference &&
argument.Kind != BoundKind.DiscardExpression)
{
TypeSymbol parameterType = UnwrapIfParamsArray(parameter, isLastParameter) is TypeSymbol t ? t : parameter.Type;
// If the problem is that a lambda isn't convertible to the given type, also report why.
// The argument and parameter type might match, but may not have same in/out modifiers
if (argument.Kind == BoundKind.UnboundLambda && refArg == refParameter)
{
((UnboundLambda)argument).GenerateAnonymousFunctionConversionError(diagnostics, parameterType);
}
else if (argument.Kind == BoundKind.MethodGroup && parameterType.TypeKind == TypeKind.Delegate &&
binder.Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(binder, (BoundMethodGroup)argument, parameterType, diagnostics))
{
// a diagnostic has been reported by ReportDelegateOrFunctionPointerMethodGroupDiagnostics
}
else if (argument.Kind == BoundKind.MethodGroup && parameterType.TypeKind == TypeKind.FunctionPointer)
{
diagnostics.Add(ErrorCode.ERR_MissingAddressOf, sourceLocation);
}
else if (argument.Kind == BoundKind.UnconvertedAddressOfOperator &&
binder.Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(binder, ((BoundUnconvertedAddressOfOperator)argument).Operand, parameterType, diagnostics))
{
// a diagnostic has been reported by ReportDelegateOrFunctionPointerMethodGroupDiagnostics
}
else
{
// There's no symbol for the argument, so we don't need a SymbolDistinguisher.
// Argument 1: cannot convert from '<null>' to 'ref int'
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
argument.Display, //'<null>' doesn't need refkind
UnwrapIfParamsArray(parameter, isLastParameter));
}
}
else if (refArg != refParameter && !(refArg == RefKind.None && refParameter == RefKind.In))
{
if (refParameter == RefKind.None || refParameter == RefKind.In)
{
// Argument {0} should not be passed with the {1} keyword
diagnostics.Add(
ErrorCode.ERR_BadArgExtraRef,
sourceLocation,
symbols,
arg + 1,
refArg.ToArgumentDisplayString());
}
else
{
// Argument {0} must be passed with the '{1}' keyword
diagnostics.Add(
ErrorCode.ERR_BadArgRef,
sourceLocation,
symbols,
arg + 1,
refParameter.ToParameterDisplayString());
}
}
else
{
Debug.Assert(argument.Kind != BoundKind.OutDeconstructVarPendingInference);
Debug.Assert(argument.Kind != BoundKind.OutVariablePendingInference);
Debug.Assert(argument.Kind != BoundKind.DiscardExpression || argument.HasExpressionType());
Debug.Assert(argument.Display != null);
if (arguments.IsExtensionMethodThisArgument(arg))
{
Debug.Assert((arg == 0) && (parm == arg));
Debug.Assert(!badArg.Result.ConversionForArg(parm).IsImplicit);
// CS1929: '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' requires a receiver of type '{3}'
diagnostics.Add(
ErrorCode.ERR_BadInstanceArgType,
sourceLocation,
symbols,
argument.Display,
name,
method,
parameter);
Debug.Assert((object)parameter == UnwrapIfParamsArray(parameter, isLastParameter), "If they ever differ, just call the method when constructing the diagnostic.");
}
else
{
// There's only one slot in the error message for the refkind + arg type, but there isn't a single
// object that contains both values, so we have to construct our own.
// NOTE: since this is a symbol, it will use the SymbolDisplay options for parameters (i.e. will
// have the same format as the display value of the parameter).
if (argument.Display is TypeSymbol argType)
{
SignatureOnlyParameterSymbol displayArg = new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(argType),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
refKind: refArg);
SymbolDistinguisher distinguisher = new SymbolDistinguisher(binder.Compilation, displayArg, UnwrapIfParamsArray(parameter, isLastParameter));
// CS1503: Argument {0}: cannot convert from '{1}' to '{2}'
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
distinguisher.First,
distinguisher.Second);
}
else
{
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
argument.Display,
UnwrapIfParamsArray(parameter, isLastParameter));
}
}
}
}
/// <summary>
/// If an argument fails to convert to the type of the corresponding parameter and that
/// parameter is a params array, then the error message should reflect the element type
/// of the params array - not the array type.
/// </summary>
private static Symbol UnwrapIfParamsArray(ParameterSymbol parameter, bool isLastParameter)
{
// We only try to unwrap parameters if they are a parameter array and are on the last position
if (parameter.IsParams && isLastParameter)
{
ArrayTypeSymbol arrayType = parameter.Type as ArrayTypeSymbol;
if ((object)arrayType != null && arrayType.IsSZArray)
{
return arrayType.ElementType;
}
}
return parameter;
}
private bool HadAmbiguousWorseMethods(BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, Location location, bool isQuery, BoundExpression receiver, string name)
{
MemberResolutionResult<TMember> worseResult1;
MemberResolutionResult<TMember> worseResult2;
// UNDONE: It is unfortunate that we simply choose the first two methods as the
// UNDONE: two to say that are ambiguous; they might not actually be ambiguous
// UNDONE: with each other. We might consider building a better heuristic here.
int nWorse = TryGetFirstTwoWorseResults(out worseResult1, out worseResult2);
if (nWorse <= 1)
{
Debug.Assert(nWorse == 0, "How is it that there is exactly one applicable but worse method, and exactly zero applicable best methods? What was better than this thing?");
return false;
}
if (isQuery)
{
// Multiple implementations of the query pattern were found for source type '{0}'. Ambiguous call to '{1}'.
diagnostics.Add(ErrorCode.ERR_QueryMultipleProviders, location, receiver.Type, name);
}
else
{
// error CS0121: The call is ambiguous between the following methods or properties: 'P.W(A)' and 'P.W(B)'
diagnostics.Add(
CreateAmbiguousCallDiagnosticInfo(
worseResult1.LeastOverriddenMember.OriginalDefinition,
worseResult2.LeastOverriddenMember.OriginalDefinition,
symbols),
location);
}
return true;
}
private int TryGetFirstTwoWorseResults(out MemberResolutionResult<TMember> first, out MemberResolutionResult<TMember> second)
{
int count = 0;
bool foundFirst = false;
bool foundSecond = false;
first = default(MemberResolutionResult<TMember>);
second = default(MemberResolutionResult<TMember>);
foreach (var res in this.ResultsBuilder)
{
if (res.Result.Kind == MemberResolutionKind.Worse)
{
count++;
if (!foundFirst)
{
first = res;
foundFirst = true;
}
else if (!foundSecond)
{
second = res;
foundSecond = true;
}
}
}
return count;
}
private bool HadAmbiguousBestMethods(BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, Location location)
{
MemberResolutionResult<TMember> validResult1;
MemberResolutionResult<TMember> validResult2;
var nValid = TryGetFirstTwoValidResults(out validResult1, out validResult2);
if (nValid <= 1)
{
Debug.Assert(nValid == 0, "Why are we doing error reporting on an overload resolution problem that had one valid result?");
return false;
}
// error CS0121: The call is ambiguous between the following methods or properties:
// 'P.Ambiguous(object, string)' and 'P.Ambiguous(string, object)'
diagnostics.Add(
CreateAmbiguousCallDiagnosticInfo(
validResult1.LeastOverriddenMember.OriginalDefinition,
validResult2.LeastOverriddenMember.OriginalDefinition,
symbols),
location);
return true;
}
private int TryGetFirstTwoValidResults(out MemberResolutionResult<TMember> first, out MemberResolutionResult<TMember> second)
{
int count = 0;
bool foundFirst = false;
bool foundSecond = false;
first = default(MemberResolutionResult<TMember>);
second = default(MemberResolutionResult<TMember>);
foreach (var res in this.ResultsBuilder)
{
if (res.Result.IsValid)
{
count++;
if (!foundFirst)
{
first = res;
foundFirst = true;
}
else if (!foundSecond)
{
second = res;
foundSecond = true;
}
}
}
return count;
}
private static DiagnosticInfoWithSymbols CreateAmbiguousCallDiagnosticInfo(Symbol first, Symbol second, ImmutableArray<Symbol> symbols)
{
var arguments = (first.ContainingNamespace != second.ContainingNamespace) ?
new object[]
{
new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat),
new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat)
} :
new object[]
{
first,
second
};
return new DiagnosticInfoWithSymbols(ErrorCode.ERR_AmbigCall, arguments, symbols);
}
[Conditional("DEBUG")]
private void AssertNone(MemberResolutionKind kind)
{
foreach (var result in this.ResultsBuilder)
{
if (result.Result.Kind == kind)
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
private MemberResolutionResult<TMember> GetFirstMemberKind(MemberResolutionKind kind)
{
foreach (var result in this.ResultsBuilder)
{
if (result.Result.Kind == kind)
{
return result;
}
}
return default(MemberResolutionResult<TMember>);
}
#if DEBUG
internal string Dump()
{
if (ResultsBuilder.Count == 0)
{
return "Overload resolution failed because the method group was empty.";
}
var sb = new StringBuilder();
if (this.Succeeded)
{
sb.AppendLine("Overload resolution succeeded and chose " + this.ValidResult.Member.ToString());
}
else if (System.Linq.Enumerable.Count(ResultsBuilder, x => x.Result.IsValid) > 1)
{
sb.AppendLine("Overload resolution failed because of ambiguous possible best methods.");
}
else if (System.Linq.Enumerable.Any(ResultsBuilder, x => (x.Result.Kind == MemberResolutionKind.TypeInferenceFailed) || (x.Result.Kind == MemberResolutionKind.TypeInferenceExtensionInstanceArgument)))
{
sb.AppendLine("Overload resolution failed (possibly) because type inference was unable to infer type parameters.");
}
sb.AppendLine("Detailed results:");
foreach (var result in ResultsBuilder)
{
sb.AppendFormat("method: {0} reason: {1}\n", result.Member.ToString(), result.Result.Kind.ToString());
}
return sb.ToString();
}
#endif
#region "Poolable"
internal static OverloadResolutionResult<TMember> GetInstance()
{
return s_pool.Allocate();
}
internal void Free()
{
this.Clear();
s_pool.Free(this);
}
//2) Expose the pool or the way to create a pool or the way to get an instance.
// for now we will expose both and figure which way works better
private static readonly ObjectPool<OverloadResolutionResult<TMember>> s_pool = CreatePool();
private static ObjectPool<OverloadResolutionResult<TMember>> CreatePool()
{
ObjectPool<OverloadResolutionResult<TMember>> pool = null;
pool = new ObjectPool<OverloadResolutionResult<TMember>>(() => new OverloadResolutionResult<TMember>(), 10);
return pool;
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
#if DEBUG
using System.Text;
#endif
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Summarizes the results of an overload resolution analysis, as described in section 7.5 of
/// the language specification. Describes whether overload resolution succeeded, and which
/// method was selected if overload resolution succeeded, as well as detailed information about
/// each method that was considered.
/// </summary>
internal class OverloadResolutionResult<TMember> where TMember : Symbol
{
private MemberResolutionResult<TMember> _bestResult;
private ThreeState _bestResultState;
internal readonly ArrayBuilder<MemberResolutionResult<TMember>> ResultsBuilder;
// Create an overload resolution result from a single result.
internal OverloadResolutionResult()
{
this.ResultsBuilder = new ArrayBuilder<MemberResolutionResult<TMember>>();
}
internal void Clear()
{
_bestResult = default(MemberResolutionResult<TMember>);
_bestResultState = ThreeState.Unknown;
this.ResultsBuilder.Clear();
}
/// <summary>
/// True if overload resolution successfully selected a single best method.
/// </summary>
public bool Succeeded
{
get
{
EnsureBestResultLoaded();
return _bestResultState == ThreeState.True && _bestResult.Result.IsValid;
}
}
/// <summary>
/// If overload resolution successfully selected a single best method, returns information
/// about that method. Otherwise returns null.
/// </summary>
public MemberResolutionResult<TMember> ValidResult
{
get
{
EnsureBestResultLoaded();
Debug.Assert(_bestResultState == ThreeState.True && _bestResult.Result.IsValid);
return _bestResult;
}
}
private void EnsureBestResultLoaded()
{
if (!_bestResultState.HasValue())
{
_bestResultState = TryGetBestResult(this.ResultsBuilder, out _bestResult);
}
}
/// <summary>
/// If there was a method that overload resolution considered better than all others,
/// returns information about that method. A method may be returned even if that method was
/// not considered a successful overload resolution, as long as it was better that any other
/// potential method considered.
/// </summary>
public MemberResolutionResult<TMember> BestResult
{
get
{
EnsureBestResultLoaded();
Debug.Assert(_bestResultState == ThreeState.True);
return _bestResult;
}
}
/// <summary>
/// Returns information about each method that was considered during overload resolution,
/// and what the results of overload resolution were for that method.
/// </summary>
public ImmutableArray<MemberResolutionResult<TMember>> Results
{
get
{
return this.ResultsBuilder.ToImmutable();
}
}
/// <summary>
/// Returns true if one or more of the members in the group are applicable. (Note that
/// Succeeded implies IsApplicable but IsApplicable does not imply Succeeded. It is possible
/// that no applicable member was better than all others.)
/// </summary>
internal bool HasAnyApplicableMember
{
get
{
foreach (var res in this.ResultsBuilder)
{
if (res.Result.IsApplicable)
{
return true;
}
}
return false;
}
}
/// <summary>
/// Returns all methods in the group that are applicable, <see cref="HasAnyApplicableMember"/>.
/// </summary>
internal ImmutableArray<TMember> GetAllApplicableMembers()
{
var result = ArrayBuilder<TMember>.GetInstance();
foreach (var res in this.ResultsBuilder)
{
if (res.Result.IsApplicable)
{
result.Add(res.Member);
}
}
return result.ToImmutableAndFree();
}
private static ThreeState TryGetBestResult(ArrayBuilder<MemberResolutionResult<TMember>> allResults, out MemberResolutionResult<TMember> best)
{
best = default(MemberResolutionResult<TMember>);
ThreeState haveBest = ThreeState.False;
foreach (var pair in allResults)
{
if (pair.Result.IsValid)
{
if (haveBest == ThreeState.True)
{
Debug.Assert(false, "How did we manage to get two methods in the overload resolution results that were both better than every other method?");
best = default(MemberResolutionResult<TMember>);
return ThreeState.False;
}
haveBest = ThreeState.True;
best = pair;
}
}
// TODO: There might be a situation in which there were no valid results but we still want to identify a "best of a bad lot" result for
// TODO: error reporting.
return haveBest;
}
/// <summary>
/// Called when overload resolution has failed. Figures out the best way to describe what went wrong.
/// </summary>
/// <remarks>
/// Overload resolution (effectively) starts out assuming that all candidates are valid and then
/// gradually disqualifies them. Therefore, our strategy will be to perform our checks in the
/// reverse order - the farther a candidate got through the process without being flagged, the
/// "better" it was.
///
/// Note that "final validation" is performed after overload resolution,
/// so final validation errors are not seen here. Final validation errors include
/// violations of constraints on method type parameters, static/instance mismatches,
/// and so on.
/// </remarks>
internal void ReportDiagnostics<T>(
Binder binder,
Location location,
SyntaxNode nodeOpt,
BindingDiagnosticBag diagnostics,
string name,
BoundExpression receiver,
SyntaxNode invokedExpression,
AnalyzedArguments arguments,
ImmutableArray<T> memberGroup, // the T is just a convenience for the caller
NamedTypeSymbol typeContainingConstructor,
NamedTypeSymbol delegateTypeBeingInvoked,
CSharpSyntaxNode queryClause = null,
bool isMethodGroupConversion = false,
RefKind? returnRefKind = null,
TypeSymbol delegateOrFunctionPointerType = null) where T : Symbol
{
Debug.Assert(!this.Succeeded, "Don't ask for diagnostic info on a successful overload resolution result.");
// Each argument must have non-null Display in case it is used in a diagnostic.
Debug.Assert(arguments.Arguments.All(a => a.Display != null));
// This kind is only used for default(MemberResolutionResult<T>), so we should never see it in
// the candidate list.
AssertNone(MemberResolutionKind.None);
var symbols = StaticCast<Symbol>.From(memberGroup);
//// PHASE 1: Valid candidates ////
// Since we're here, we know that there isn't exactly one applicable candidate. There may,
// however, be more than one. We'll check for that first, since applicable candidates are
// always better than inapplicable candidates.
if (HadAmbiguousBestMethods(diagnostics, symbols, location))
{
return;
}
// Since we didn't return, we know that there aren't two or more applicable candidates.
// From above, we know there isn't exactly one either. Therefore, there must not be any
// applicable candidates.
AssertNone(MemberResolutionKind.ApplicableInNormalForm);
AssertNone(MemberResolutionKind.ApplicableInExpandedForm);
// There are two ways that otherwise-applicable candidates can be ruled out by overload resolution:
// a) there is another applicable candidate that is strictly better, or
// b) there is another applicable candidate from a more derived type.
// There can't be exactly one such candidate, since that would the existence of some better
// applicable candidate, which would have either won or been detected above. It is possible,
// however, that there are multiple candidates that are worse than each other in a cycle.
// This might sound like a paradox, but it is in fact possible. Because there are
// intransitivities in convertibility (where A-->B, B-->C and C-->A but none of the
// opposite conversions are legal) there are also intransitivities in betterness.
// (Obviously, there can't be a LessDerived cycle, since we break type hierarchy cycles during
// symbol table construction.)
if (HadAmbiguousWorseMethods(diagnostics, symbols, location, queryClause != null, receiver, name))
{
return;
}
// Since we didn't return, we know that there aren't two or "worse" candidates. As above,
// there also can't be a single one. Therefore, there are none.
AssertNone(MemberResolutionKind.Worse);
// If there's a less-derived candidate, it must be less derived than some applicable or
// "worse" candidate. Since there are none of those, there must not be any less-derived
// candidates either.
AssertNone(MemberResolutionKind.LessDerived);
//// PHASE 2: Applicability failures ////
// Overload resolution performed these checks just before weeding out less-derived and worse candidates.
// If we got as far as converting a lambda to a delegate type, and we failed to
// do so, then odds are extremely good that the failure is the ultimate cause
// of the overload resolution failing to find any applicable method. Report
// the errors out of each lambda argument, if there were any.
// NOTE: There isn't a MemberResolutionKind for this error condition.
if (HadLambdaConversionError(diagnostics, arguments))
{
return;
}
// If there is any instance(or alternatively static) method accessed through a
// type(or alternatively expression) then the first such method is the best bad method.
// To retain existing behavior, we use the location of the invoked expression for the error.
if (HadStaticInstanceMismatch(diagnostics, symbols, invokedExpression?.GetLocation() ?? location, binder, receiver, nodeOpt, delegateOrFunctionPointerType))
{
return;
}
// When overload resolution is being done to resolve a method group conversion (to a delegate type),
// if there is any method being converted to a delegate type, but the method's return
// ref kind does not match the delegate, then the first such method is the best bad method.
// Otherwise if there is any method whose return type does not match the delegate, then the
// first such method is the best bad method
if (isMethodGroupConversion && returnRefKind != null &&
HadReturnMismatch(location, diagnostics, returnRefKind.GetValueOrDefault(), delegateOrFunctionPointerType))
{
return;
}
// Otherwise, if there is any such method where type inference succeeded but inferred
// type arguments that violate the constraints on the method, then the first such method is
// the best bad method.
if (HadConstraintFailure(location, diagnostics))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.ConstraintFailure);
// Otherwise, if there is any such method that has a bad argument conversion or out/ref mismatch
// then the first such method found is the best bad method.
if (HadBadArguments(diagnostics, binder, name, arguments, symbols, location, binder.Flags, isMethodGroupConversion))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.BadArgumentConversion);
// Otherwise, if there is any such method where type inference succeeded but inferred
// a parameter type that violates its own constraints then the first such method is
// the best bad method.
if (HadConstructedParameterFailedConstraintCheck(binder.Conversions, binder.Compilation, diagnostics, location))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.ConstructedParameterFailedConstraintCheck);
// Otherwise, if there is any such method where type inference succeeded but inferred
// an inaccessible type then the first such method found is the best bad method.
if (InaccessibleTypeArgument(diagnostics, symbols, location))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.InaccessibleTypeArgument);
// Otherwise, if there is any such method where type inference failed then the
// first such method is the best bad method.
if (TypeInferenceFailed(binder, diagnostics, symbols, receiver, arguments, location, queryClause))
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.TypeInferenceFailed);
AssertNone(MemberResolutionKind.TypeInferenceExtensionInstanceArgument);
//// PHASE 3: Use site errors ////
// Overload resolution checks for use site errors between argument analysis and applicability testing.
// Otherwise, if there is any such method that cannot be used because it is
// in an unreferenced assembly then the first such method is the best bad method.
if (UseSiteError())
{
return;
}
// Since we didn't return...
AssertNone(MemberResolutionKind.UseSiteError);
//// PHASE 4: Argument analysis failures and unsupported metadata ////
// The first to checks in overload resolution are for unsupported metadata (Symbol.HasUnsupportedMetadata)
// and argument analysis. We don't want to report unsupported metadata unless nothing else went wrong -
// otherwise we'd report errors about losing candidates, effectively "pulling in" unnecessary assemblies.
bool supportedRequiredParameterMissingConflicts = false;
MemberResolutionResult<TMember> firstSupported = default(MemberResolutionResult<TMember>);
MemberResolutionResult<TMember> firstUnsupported = default(MemberResolutionResult<TMember>);
var supportedInPriorityOrder = new MemberResolutionResult<TMember>[7]; // from highest to lowest priority
const int duplicateNamedArgumentPriority = 0;
const int requiredParameterMissingPriority = 1;
const int nameUsedForPositionalPriority = 2;
const int noCorrespondingNamedParameterPriority = 3;
const int noCorrespondingParameterPriority = 4;
const int badNonTrailingNamedArgumentPriority = 5;
const int wrongCallingConventionPriority = 6;
foreach (MemberResolutionResult<TMember> result in this.ResultsBuilder)
{
switch (result.Result.Kind)
{
case MemberResolutionKind.UnsupportedMetadata:
if (firstSupported.IsNull)
{
firstUnsupported = result;
}
break;
case MemberResolutionKind.NoCorrespondingNamedParameter:
if (supportedInPriorityOrder[noCorrespondingNamedParameterPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[noCorrespondingNamedParameterPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[noCorrespondingNamedParameterPriority] = result;
}
break;
case MemberResolutionKind.NoCorrespondingParameter:
if (supportedInPriorityOrder[noCorrespondingParameterPriority].IsNull)
{
supportedInPriorityOrder[noCorrespondingParameterPriority] = result;
}
break;
case MemberResolutionKind.RequiredParameterMissing:
if (supportedInPriorityOrder[requiredParameterMissingPriority].IsNull)
{
Debug.Assert(!supportedRequiredParameterMissingConflicts);
supportedInPriorityOrder[requiredParameterMissingPriority] = result;
}
else
{
supportedRequiredParameterMissingConflicts = true;
}
break;
case MemberResolutionKind.NameUsedForPositional:
if (supportedInPriorityOrder[nameUsedForPositionalPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[nameUsedForPositionalPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[nameUsedForPositionalPriority] = result;
}
break;
case MemberResolutionKind.BadNonTrailingNamedArgument:
if (supportedInPriorityOrder[badNonTrailingNamedArgumentPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[badNonTrailingNamedArgumentPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[badNonTrailingNamedArgumentPriority] = result;
}
break;
case MemberResolutionKind.DuplicateNamedArgument:
{
if (supportedInPriorityOrder[duplicateNamedArgumentPriority].IsNull ||
result.Result.BadArgumentsOpt[0] > supportedInPriorityOrder[duplicateNamedArgumentPriority].Result.BadArgumentsOpt[0])
{
supportedInPriorityOrder[duplicateNamedArgumentPriority] = result;
}
}
break;
case MemberResolutionKind.WrongCallingConvention:
{
if (supportedInPriorityOrder[wrongCallingConventionPriority].IsNull)
{
supportedInPriorityOrder[wrongCallingConventionPriority] = result;
}
}
break;
default:
// Based on the asserts above, we know that only the kinds above
// are possible at this point. This should only throw if a new
// kind is added without appropriate checking above.
throw ExceptionUtilities.UnexpectedValue(result.Result.Kind);
}
}
foreach (var supported in supportedInPriorityOrder)
{
if (supported.IsNotNull)
{
firstSupported = supported;
break;
}
}
// If there are any supported candidates, we don't care about unsupported candidates.
if (firstSupported.IsNotNull)
{
if (firstSupported.Member is FunctionPointerMethodSymbol
&& firstSupported.Result.Kind == MemberResolutionKind.NoCorrespondingNamedParameter)
{
int badArg = firstSupported.Result.BadArgumentsOpt[0];
Debug.Assert(arguments.Names[badArg].HasValue);
Location badName = arguments.Names[badArg].GetValueOrDefault().Location;
diagnostics.Add(ErrorCode.ERR_FunctionPointersCannotBeCalledWithNamedArguments, badName);
return;
}
// If there are multiple supported candidates, we don't have a good way to choose the best
// one so we report a general diagnostic (below).
else if (!(firstSupported.Result.Kind == MemberResolutionKind.RequiredParameterMissing && supportedRequiredParameterMissingConflicts)
&& !isMethodGroupConversion
// Function pointer type symbols don't have named parameters, so we just want to report a general mismatched parameter
// count instead of name errors.
&& (firstSupported.Member is not FunctionPointerMethodSymbol))
{
switch (firstSupported.Result.Kind)
{
// Otherwise, if there is any such method that has a named argument and a positional
// argument for the same parameter then the first such method is the best bad method.
case MemberResolutionKind.NameUsedForPositional:
ReportNameUsedForPositional(firstSupported, diagnostics, arguments, symbols);
return;
// Otherwise, if there is any such method that has a named argument that corresponds
// to no parameter then the first such method is the best bad method.
case MemberResolutionKind.NoCorrespondingNamedParameter:
ReportNoCorrespondingNamedParameter(firstSupported, name, diagnostics, arguments, delegateTypeBeingInvoked, symbols);
return;
// Otherwise, if there is any such method that has a required parameter
// but no argument was supplied for it then the first such method is
// the best bad method.
case MemberResolutionKind.RequiredParameterMissing:
// CONSIDER: for consistency with dev12, we would goto default except in omitted ref cases.
ReportMissingRequiredParameter(firstSupported, diagnostics, delegateTypeBeingInvoked, symbols, location);
return;
// NOTE: For some reason, there is no specific handling for this result kind.
case MemberResolutionKind.NoCorrespondingParameter:
break;
// Otherwise, if there is any such method that has a named argument was used out-of-position
// and followed by unnamed arguments.
case MemberResolutionKind.BadNonTrailingNamedArgument:
ReportBadNonTrailingNamedArgument(firstSupported, diagnostics, arguments, symbols);
return;
case MemberResolutionKind.DuplicateNamedArgument:
ReportDuplicateNamedArgument(firstSupported, diagnostics, arguments);
return;
}
}
else if (firstSupported.Result.Kind == MemberResolutionKind.WrongCallingConvention)
{
ReportWrongCallingConvention(location, diagnostics, symbols, firstSupported, ((FunctionPointerTypeSymbol)delegateOrFunctionPointerType).Signature);
return;
}
}
else if (firstUnsupported.IsNotNull)
{
// Otherwise, if there is any such method that cannot be used because it is
// unsupported by the language then the first such method is the best bad method.
// This is the first kind of problem overload resolution checks for, so it should
// be the last MemberResolutionKind we check for. Candidates with this kind
// failed the soonest.
// CONSIDER: report his on every unsupported candidate?
ReportUnsupportedMetadata(location, diagnostics, symbols, firstUnsupported);
return;
}
// If the user provided a number of arguments that works for no possible method in the method
// group then we give an error saying that. Every method will have an error of the form
// "missing required parameter" or "argument corresponds to no parameter", and therefore we
// have no way of choosing a "best bad method" to report the error on. We should simply
// say that no possible method can take the given number of arguments.
// CAVEAT: For method group conversions, the caller reports a different diagnostics.
if (!isMethodGroupConversion)
{
ReportBadParameterCount(diagnostics, name, arguments, symbols, location, typeContainingConstructor, delegateTypeBeingInvoked);
}
}
private static void ReportUnsupportedMetadata(Location location, BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, MemberResolutionResult<TMember> firstUnsupported)
{
DiagnosticInfo diagInfo = firstUnsupported.Member.GetUseSiteInfo().DiagnosticInfo;
Debug.Assert(diagInfo != null);
Debug.Assert(diagInfo.Severity == DiagnosticSeverity.Error);
// Attach symbols to the diagnostic info.
diagInfo = new DiagnosticInfoWithSymbols(
(ErrorCode)diagInfo.Code,
diagInfo.Arguments,
symbols);
Symbol.ReportUseSiteDiagnostic(diagInfo, diagnostics, location);
}
private static void ReportWrongCallingConvention(Location location, BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, MemberResolutionResult<TMember> firstSupported, MethodSymbol target)
{
Debug.Assert(firstSupported.Result.Kind == MemberResolutionKind.WrongCallingConvention);
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_WrongFuncPtrCallingConvention,
new object[] { firstSupported.Member, target.CallingConvention },
symbols), location);
}
private bool UseSiteError()
{
var bad = GetFirstMemberKind(MemberResolutionKind.UseSiteError);
if (bad.IsNull)
{
return false;
}
Debug.Assert(bad.Member.GetUseSiteInfo().DiagnosticInfo.Severity == DiagnosticSeverity.Error,
"Why did we use MemberResolutionKind.UseSiteError if we didn't have a use site error?");
// Use site errors are reported unconditionally in PerformMemberOverloadResolution/PerformObjectCreationOverloadResolution.
return true;
}
private bool InaccessibleTypeArgument(
BindingDiagnosticBag diagnostics,
ImmutableArray<Symbol> symbols,
Location location)
{
var inaccessible = GetFirstMemberKind(MemberResolutionKind.InaccessibleTypeArgument);
if (inaccessible.IsNull)
{
return false;
}
// error CS0122: 'M<X>(I<X>)' is inaccessible due to its protection level
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_BadAccess,
new object[] { inaccessible.Member },
symbols), location);
return true;
}
private bool HadStaticInstanceMismatch(
BindingDiagnosticBag diagnostics,
ImmutableArray<Symbol> symbols,
Location location,
Binder binder,
BoundExpression receiverOpt,
SyntaxNode nodeOpt,
TypeSymbol delegateOrFunctionPointerType)
{
var staticInstanceMismatch = GetFirstMemberKind(MemberResolutionKind.StaticInstanceMismatch);
if (staticInstanceMismatch.IsNull)
{
return false;
}
Symbol symbol = staticInstanceMismatch.Member;
// Certain compiler-generated invocations produce custom diagnostics.
if (receiverOpt?.Kind == BoundKind.QueryClause)
{
// Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found.
diagnostics.Add(ErrorCode.ERR_QueryNoProvider, location, receiverOpt.Type, symbol.Name);
}
else if (binder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod))
{
diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, location, symbol);
}
else if (nodeOpt?.Kind() == SyntaxKind.AwaitExpression && symbol.Name == WellKnownMemberNames.GetAwaiter)
{
diagnostics.Add(ErrorCode.ERR_BadAwaitArg, location, receiverOpt.Type);
}
else if (delegateOrFunctionPointerType is FunctionPointerTypeSymbol)
{
diagnostics.Add(ErrorCode.ERR_FuncPtrMethMustBeStatic, location, symbol);
}
else
{
ErrorCode errorCode =
symbol.RequiresInstanceReceiver()
? Binder.WasImplicitReceiver(receiverOpt) && binder.InFieldInitializer && !binder.BindingTopLevelScriptCode
? ErrorCode.ERR_FieldInitRefNonstatic
: ErrorCode.ERR_ObjectRequired
: ErrorCode.ERR_ObjectProhibited;
// error CS0176: Member 'Program.M(B)' cannot be accessed with an instance reference; qualify it with a type name instead
// -or-
// error CS0120: An object reference is required for the non-static field, method, or property 'Program.M(B)'
diagnostics.Add(new DiagnosticInfoWithSymbols(
errorCode,
new object[] { symbol },
symbols), location);
}
return true;
}
private bool HadReturnMismatch(Location location, BindingDiagnosticBag diagnostics, RefKind refKind, TypeSymbol delegateOrFunctionPointerType)
{
var mismatch = GetFirstMemberKind(MemberResolutionKind.WrongRefKind);
if (!mismatch.IsNull)
{
diagnostics.Add(delegateOrFunctionPointerType.IsFunctionPointer() ? ErrorCode.ERR_FuncPtrRefMismatch : ErrorCode.ERR_DelegateRefMismatch,
location, mismatch.Member, delegateOrFunctionPointerType);
return true;
}
mismatch = GetFirstMemberKind(MemberResolutionKind.WrongReturnType);
if (!mismatch.IsNull)
{
var method = (MethodSymbol)(Symbol)mismatch.Member;
diagnostics.Add(ErrorCode.ERR_BadRetType, location, method, method.ReturnType);
return true;
}
return false;
}
private bool HadConstraintFailure(Location location, BindingDiagnosticBag diagnostics)
{
var constraintFailure = GetFirstMemberKind(MemberResolutionKind.ConstraintFailure);
if (constraintFailure.IsNull)
{
return false;
}
foreach (var pair in constraintFailure.Result.ConstraintFailureDiagnostics)
{
if (pair.UseSiteInfo.DiagnosticInfo is object)
{
diagnostics.Add(new CSDiagnostic(pair.UseSiteInfo.DiagnosticInfo, location));
}
}
return true;
}
private bool TypeInferenceFailed(
Binder binder,
BindingDiagnosticBag diagnostics,
ImmutableArray<Symbol> symbols,
BoundExpression receiver,
AnalyzedArguments arguments,
Location location,
CSharpSyntaxNode queryClause = null)
{
var inferenceFailed = GetFirstMemberKind(MemberResolutionKind.TypeInferenceFailed);
if (inferenceFailed.IsNotNull)
{
if (queryClause != null)
{
Binder.ReportQueryInferenceFailed(queryClause, inferenceFailed.Member.Name, receiver, arguments, symbols, diagnostics);
}
else
{
// error CS0411: The type arguments for method 'M<T>(T)' cannot be inferred
// from the usage. Try specifying the type arguments explicitly.
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_CantInferMethTypeArgs,
new object[] { inferenceFailed.Member },
symbols), location);
}
return true;
}
inferenceFailed = GetFirstMemberKind(MemberResolutionKind.TypeInferenceExtensionInstanceArgument);
if (inferenceFailed.IsNotNull)
{
Debug.Assert(arguments.Arguments.Count > 0);
var instanceArgument = arguments.Arguments[0];
if (queryClause != null)
{
binder.ReportQueryLookupFailed(queryClause, instanceArgument, inferenceFailed.Member.Name, symbols, diagnostics);
}
else
{
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_NoSuchMemberOrExtension,
new object[] { instanceArgument.Type, inferenceFailed.Member.Name },
symbols), location);
}
return true;
}
return false;
}
private static void ReportNameUsedForPositional(
MemberResolutionResult<TMember> bad,
BindingDiagnosticBag diagnostics,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols)
{
int badArg = bad.Result.BadArgumentsOpt[0];
// We would not have gotten this error had there not been a named argument.
Debug.Assert(arguments.Names.Count > badArg);
Debug.Assert(arguments.Names[badArg].HasValue);
(string badName, Location location) = arguments.Names[badArg].GetValueOrDefault();
Debug.Assert(badName != null);
// Named argument 'x' specifies a parameter for which a positional argument has already been given
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_NamedArgumentUsedInPositional,
new object[] { badName },
symbols), location);
}
private static void ReportBadNonTrailingNamedArgument(
MemberResolutionResult<TMember> bad,
BindingDiagnosticBag diagnostics,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols)
{
int badArg = bad.Result.BadArgumentsOpt[0];
// We would not have gotten this error had there not been a named argument.
Debug.Assert(arguments.Names.Count > badArg);
Debug.Assert(arguments.Names[badArg].HasValue);
(string badName, Location location) = arguments.Names[badArg].GetValueOrDefault();
Debug.Assert(badName != null);
// Named argument 'x' is used out-of-position but is followed by an unnamed argument.
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_BadNonTrailingNamedArgument,
new object[] { badName },
symbols), location);
}
private static void ReportDuplicateNamedArgument(MemberResolutionResult<TMember> result, BindingDiagnosticBag diagnostics, AnalyzedArguments arguments)
{
Debug.Assert(result.Result.BadArgumentsOpt.Length == 1);
Debug.Assert(arguments.Names[result.Result.BadArgumentsOpt[0]].HasValue);
(string name, Location location) = arguments.Names[result.Result.BadArgumentsOpt[0]].GetValueOrDefault();
Debug.Assert(name != null);
// CS: Named argument '{0}' cannot be specified multiple times
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_DuplicateNamedArgument, name), location);
}
private static void ReportNoCorrespondingNamedParameter(
MemberResolutionResult<TMember> bad,
string methodName,
BindingDiagnosticBag diagnostics,
AnalyzedArguments arguments,
NamedTypeSymbol delegateTypeBeingInvoked,
ImmutableArray<Symbol> symbols)
{
// We know that there is at least one method that had a number of arguments
// passed that was valid for *some* method in the candidate set. Given that
// fact, we seek the *best* method in the candidate set to report the error
// on. If we have a method that has a valid number of arguments, but the
// call was inapplicable because there was a bad name, that's a candidate
// for the "best" overload.
int badArg = bad.Result.BadArgumentsOpt[0];
// We would not have gotten this error had there not been a named argument.
Debug.Assert(arguments.Names.Count > badArg);
Debug.Assert(arguments.Names[badArg].HasValue);
(string badName, Location location) = arguments.Names[badArg].GetValueOrDefault();
Debug.Assert(badName != null);
// error CS1739: The best overload for 'M' does not have a parameter named 'x'
// Error CS1746: The delegate 'D' does not have a parameter named 'x'
ErrorCode code = (object)delegateTypeBeingInvoked != null ?
ErrorCode.ERR_BadNamedArgumentForDelegateInvoke :
ErrorCode.ERR_BadNamedArgument;
object obj = (object)delegateTypeBeingInvoked ?? methodName;
diagnostics.Add(new DiagnosticInfoWithSymbols(
code,
new object[] { obj, badName },
symbols), location);
}
private static void ReportMissingRequiredParameter(
MemberResolutionResult<TMember> bad,
BindingDiagnosticBag diagnostics,
NamedTypeSymbol delegateTypeBeingInvoked,
ImmutableArray<Symbol> symbols,
Location location)
{
// We know that there is at least one method that had a number of arguments
// passed that was valid for *some* method in the candidate set. Given that
// fact, we seek the *best* method in the candidate set to report the error
// on. If we have a method that has a valid number of arguments, but the
// call was inapplicable because a required parameter does not have a
// corresponding argument then that's a candidate for the "best" overload.
//
// For example, you might have M(int x, int y, int z = 3) and a call
// M(1, z:4) -- the error cannot be "no overload of M takes 2 arguments"
// because M does take two arguments; M(1, 2) would be legal. The
// error instead has to be that there was no argument corresponding
// to required formal parameter 'y'.
TMember badMember = bad.Member;
ImmutableArray<ParameterSymbol> parameters = badMember.GetParameters();
int badParamIndex = bad.Result.BadParameter;
string badParamName;
if (badParamIndex == parameters.Length)
{
Debug.Assert(badMember.Kind == SymbolKind.Method);
Debug.Assert(((MethodSymbol)(object)badMember).IsVararg);
badParamName = SyntaxFacts.GetText(SyntaxKind.ArgListKeyword);
}
else
{
badParamName = parameters[badParamIndex].Name;
}
// There is no argument given that corresponds to the required formal parameter '{0}' of '{1}'
object obj = (object)delegateTypeBeingInvoked ?? badMember;
diagnostics.Add(new DiagnosticInfoWithSymbols(
ErrorCode.ERR_NoCorrespondingArgument,
new object[] { badParamName, obj },
symbols), location);
}
private static void ReportBadParameterCount(
BindingDiagnosticBag diagnostics,
string name,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols,
Location location,
NamedTypeSymbol typeContainingConstructor,
NamedTypeSymbol delegateTypeBeingInvoked)
{
// error CS1501: No overload for method 'M' takes n arguments
// error CS1729: 'M' does not contain a constructor that takes n arguments
// error CS1593: Delegate 'M' does not take n arguments
// error CS8757: Function pointer 'M' does not take n arguments
FunctionPointerMethodSymbol functionPointerMethodBeingInvoked = symbols.IsDefault || symbols.Length != 1
? null
: symbols[0] as FunctionPointerMethodSymbol;
(ErrorCode code, object target) = (typeContainingConstructor, delegateTypeBeingInvoked, functionPointerMethodBeingInvoked) switch
{
(object t, _, _) => (ErrorCode.ERR_BadCtorArgCount, t),
(_, object t, _) => (ErrorCode.ERR_BadDelArgCount, t),
(_, _, object t) => (ErrorCode.ERR_BadFuncPointerArgCount, t),
_ => (ErrorCode.ERR_BadArgCount, name)
};
int argCount = arguments.Arguments.Count;
if (arguments.IsExtensionMethodInvocation)
{
argCount--;
}
diagnostics.Add(new DiagnosticInfoWithSymbols(
code,
new object[] { target, argCount },
symbols), location);
return;
}
private bool HadConstructedParameterFailedConstraintCheck(
ConversionsBase conversions,
CSharpCompilation compilation,
BindingDiagnosticBag diagnostics,
Location location)
{
// We know that there is at least one method that had a number of arguments
// passed that was valid for *some* method in the candidate set. Given that
// fact, we seek the *best* method in the candidate set to report the error
// on. If we have a generic method that has a valid number of arguments, but the
// call was inapplicable because a formal parameter type failed to meet its
// constraints, give an error.
//
// That could happen like this:
//
// void Q<T>(T t1, Nullable<T> t2) where T : struct
//
// Q("", null);
//
// Every required parameter has a corresponding argument. Type inference succeeds and infers
// that T is string. Each argument is convertible to the corresponding formal parameter type.
// What makes this a not-applicable candidate is not that the constraint on T is violated, but
// rather that the constraint on *Nullable<T>* is violated; Nullable<string> is not a legal
// type, and so this is not an applicable candidate.
//
// In language versions before the feature 'ImprovedOverloadCandidates' was added to the language,
// checking whether constraints are violated *on T in Q<T>* occurs *after* overload resolution
// successfully chooses a unique best method; but with the addition of the
// feature 'ImprovedOverloadCandidates', constraint checks on the method's own type arguments
// occurs during candidate selection.
//
// Note that this failure need not involve type inference; Q<string>(null, null) would also be
// illegal for the same reason.
//
// The question then arises as to what error to report here. The native compiler reports that
// the constraint is violated on the method, even though the fact that precipitates the
// failure of overload resolution to classify this as an applicable candidate is the constraint
// violation on Nullable<T>. Most of the time this is actually a pretty sensible error message;
// if you say Q<string>(...) then it seems reasonable to give an error that says that string is
// bad for Q, not that it is bad for its formal parameters under construction. Since the compiler
// will not allow Q<T> to be declared without a constraint that ensures that Nullable<T>'s
// constraints are met, typically a failure to provide a type argument that works for the
// formal parameter type will also be a failure for the method type parameter.
//
// However, there could be error recovery scenarios. Suppose instead we had said
//
// void Q<T>(T t1, Nullable<T> t2)
//
// with no constraint on T. We will give an error at declaration time, but if later we
// are asked to provide an analysis of Q<string>("", null), the right thing to do is NOT
// to say "constraint is violated on T in Q<T>" because there is no constraint to be
// violated here. The error is (1) that the constraint is violated on Nullable<T> and
// (2) that there is a constraint missing on Q<T>.
//
// Another error-recovery scenario in which the method's constraint is not violated:
//
// struct C<U> where U : struct {}
// ...
// void Q<T>(Nullable<T> nt) where T : struct {}
// ...
// Q<C<string>>(null);
//
// C<string> is clearly an error, but equally clearly it does not violate the constraint
// on T because it is a struct. If we attempt overload resolution then overload resolution
// will say that Q<C<string>> is not an applicable candidate because N<C<string>> is not
// a valid type. N is not the problem; C<string> is a struct. C<string> is the problem.
//
// See test case CS0310ERR_NewConstraintNotSatisfied02 for an even more complex version
// of this flavor of error recovery.
var result = GetFirstMemberKind(MemberResolutionKind.ConstructedParameterFailedConstraintCheck);
if (result.IsNull)
{
return false;
}
// We would not have gotten as far as type inference succeeding if the argument count
// was invalid.
// Normally a failure to meet constraints on a formal parameter type is also a failure
// to meet constraints on the method's type argument. See if that's the case; if it
// is, then just report that error.
MethodSymbol method = (MethodSymbol)(Symbol)result.Member;
if (!method.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, location, diagnostics)))
{
// The error is already reported into the diagnostics bag.
return true;
}
// We are in the unusual position that a constraint has been violated on a formal parameter type
// without being violated on the method. Report that the constraint is violated on the
// formal parameter type.
TypeSymbol formalParameterType = method.GetParameterType(result.Result.BadParameter);
formalParameterType.CheckAllConstraints(new ConstraintsHelper.CheckConstraintsArgsBoxed((CSharpCompilation)compilation, conversions, includeNullability: false, location, diagnostics));
return true;
}
private static bool HadLambdaConversionError(BindingDiagnosticBag diagnostics, AnalyzedArguments arguments)
{
bool hadError = false;
foreach (var argument in arguments.Arguments)
{
if (argument.Kind == BoundKind.UnboundLambda)
{
hadError |= ((UnboundLambda)argument).GenerateSummaryErrors(diagnostics);
}
}
return hadError;
}
private bool HadBadArguments(
BindingDiagnosticBag diagnostics,
Binder binder,
string name,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols,
Location location,
BinderFlags flags,
bool isMethodGroupConversion)
{
var badArg = GetFirstMemberKind(MemberResolutionKind.BadArgumentConversion);
if (badArg.IsNull)
{
return false;
}
if (isMethodGroupConversion)
{
return true;
}
var method = badArg.Member;
// The best overloaded method match for '{0}' has some invalid arguments
// Since we have bad arguments to report, there is no need to report an error on the invocation itself.
//var di = new DiagnosticInfoWithSymbols(
// ErrorCode.ERR_BadArgTypes,
// new object[] { badArg.Method },
// symbols);
//
if (flags.Includes(BinderFlags.CollectionInitializerAddMethod))
{
// However, if we are binding the collection initializer Add method, we do want to generate
// ErrorCode.ERR_BadArgTypesForCollectionAdd or ErrorCode.ERR_InitializerAddHasParamModifiers
// as there is no explicit call to Add method.
foreach (var parameter in method.GetParameters())
{
if (parameter.RefKind != RefKind.None)
{
// The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
diagnostics.Add(ErrorCode.ERR_InitializerAddHasParamModifiers, location, symbols, method);
return true;
}
}
// The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
diagnostics.Add(ErrorCode.ERR_BadArgTypesForCollectionAdd, location, symbols, method);
}
foreach (var arg in badArg.Result.BadArgumentsOpt)
{
ReportBadArgumentError(diagnostics, binder, name, arguments, symbols, location, badArg, method, arg);
}
return true;
}
private static void ReportBadArgumentError(
BindingDiagnosticBag diagnostics,
Binder binder,
string name,
AnalyzedArguments arguments,
ImmutableArray<Symbol> symbols,
Location location,
MemberResolutionResult<TMember> badArg,
TMember method,
int arg)
{
BoundExpression argument = arguments.Argument(arg);
if (argument.HasAnyErrors)
{
// If the argument had an error reported then do not report further errors for
// overload resolution failure.
return;
}
int parm = badArg.Result.ParameterFromArgument(arg);
SourceLocation sourceLocation = new SourceLocation(argument.Syntax);
// Early out: if the bad argument is an __arglist parameter then simply report that:
if (method.GetIsVararg() && parm == method.GetParameterCount())
{
// NOTE: No SymbolDistinguisher required, since one of the arguments is "__arglist".
// CS1503: Argument {0}: cannot convert from '{1}' to '{2}'
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
argument.Display,
"__arglist");
return;
}
ParameterSymbol parameter = method.GetParameters()[parm];
bool isLastParameter = method.GetParameterCount() == parm + 1; // This is used to later decide if we need to try to unwrap a params array
RefKind refArg = arguments.RefKind(arg);
RefKind refParameter = parameter.RefKind;
if (arguments.IsExtensionMethodThisArgument(arg))
{
Debug.Assert(refArg == RefKind.None);
if (refParameter == RefKind.Ref || refParameter == RefKind.In)
{
// For ref and ref-readonly extension methods, we omit the "ref" modifier on receiver arguments.
// Setting the correct RefKind for finding the correct diagnostics message.
// For other ref kinds, keeping it as it is to find mismatch errors.
refArg = refParameter;
}
}
// If the expression is untyped because it is a lambda, anonymous method, method group or null
// then we never want to report the error "you need a ref on that thing". Rather, we want to
// say that you can't convert "null" to "ref int".
if (!argument.HasExpressionType() &&
argument.Kind != BoundKind.OutDeconstructVarPendingInference &&
argument.Kind != BoundKind.OutVariablePendingInference &&
argument.Kind != BoundKind.DiscardExpression)
{
TypeSymbol parameterType = UnwrapIfParamsArray(parameter, isLastParameter) is TypeSymbol t ? t : parameter.Type;
// If the problem is that a lambda isn't convertible to the given type, also report why.
// The argument and parameter type might match, but may not have same in/out modifiers
if (argument.Kind == BoundKind.UnboundLambda && refArg == refParameter)
{
((UnboundLambda)argument).GenerateAnonymousFunctionConversionError(diagnostics, parameterType);
}
else if (argument.Kind == BoundKind.MethodGroup && parameterType.TypeKind == TypeKind.Delegate &&
binder.Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(binder, (BoundMethodGroup)argument, parameterType, diagnostics))
{
// a diagnostic has been reported by ReportDelegateOrFunctionPointerMethodGroupDiagnostics
}
else if (argument.Kind == BoundKind.MethodGroup && parameterType.TypeKind == TypeKind.FunctionPointer)
{
diagnostics.Add(ErrorCode.ERR_MissingAddressOf, sourceLocation);
}
else if (argument.Kind == BoundKind.UnconvertedAddressOfOperator &&
binder.Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(binder, ((BoundUnconvertedAddressOfOperator)argument).Operand, parameterType, diagnostics))
{
// a diagnostic has been reported by ReportDelegateOrFunctionPointerMethodGroupDiagnostics
}
else
{
// There's no symbol for the argument, so we don't need a SymbolDistinguisher.
// Argument 1: cannot convert from '<null>' to 'ref int'
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
argument.Display, //'<null>' doesn't need refkind
UnwrapIfParamsArray(parameter, isLastParameter));
}
}
else if (refArg != refParameter && !(refArg == RefKind.None && refParameter == RefKind.In))
{
if (refParameter == RefKind.None || refParameter == RefKind.In)
{
// Argument {0} should not be passed with the {1} keyword
diagnostics.Add(
ErrorCode.ERR_BadArgExtraRef,
sourceLocation,
symbols,
arg + 1,
refArg.ToArgumentDisplayString());
}
else
{
// Argument {0} must be passed with the '{1}' keyword
diagnostics.Add(
ErrorCode.ERR_BadArgRef,
sourceLocation,
symbols,
arg + 1,
refParameter.ToParameterDisplayString());
}
}
else
{
Debug.Assert(argument.Kind != BoundKind.OutDeconstructVarPendingInference);
Debug.Assert(argument.Kind != BoundKind.OutVariablePendingInference);
Debug.Assert(argument.Kind != BoundKind.DiscardExpression || argument.HasExpressionType());
Debug.Assert(argument.Display != null);
if (arguments.IsExtensionMethodThisArgument(arg))
{
Debug.Assert((arg == 0) && (parm == arg));
Debug.Assert(!badArg.Result.ConversionForArg(parm).IsImplicit);
// CS1929: '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' requires a receiver of type '{3}'
diagnostics.Add(
ErrorCode.ERR_BadInstanceArgType,
sourceLocation,
symbols,
argument.Display,
name,
method,
parameter);
Debug.Assert((object)parameter == UnwrapIfParamsArray(parameter, isLastParameter), "If they ever differ, just call the method when constructing the diagnostic.");
}
else
{
// There's only one slot in the error message for the refkind + arg type, but there isn't a single
// object that contains both values, so we have to construct our own.
// NOTE: since this is a symbol, it will use the SymbolDisplay options for parameters (i.e. will
// have the same format as the display value of the parameter).
if (argument.Display is TypeSymbol argType)
{
SignatureOnlyParameterSymbol displayArg = new SignatureOnlyParameterSymbol(
TypeWithAnnotations.Create(argType),
ImmutableArray<CustomModifier>.Empty,
isParams: false,
refKind: refArg);
SymbolDistinguisher distinguisher = new SymbolDistinguisher(binder.Compilation, displayArg, UnwrapIfParamsArray(parameter, isLastParameter));
// CS1503: Argument {0}: cannot convert from '{1}' to '{2}'
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
distinguisher.First,
distinguisher.Second);
}
else
{
diagnostics.Add(
ErrorCode.ERR_BadArgType,
sourceLocation,
symbols,
arg + 1,
argument.Display,
UnwrapIfParamsArray(parameter, isLastParameter));
}
}
}
}
/// <summary>
/// If an argument fails to convert to the type of the corresponding parameter and that
/// parameter is a params array, then the error message should reflect the element type
/// of the params array - not the array type.
/// </summary>
private static Symbol UnwrapIfParamsArray(ParameterSymbol parameter, bool isLastParameter)
{
// We only try to unwrap parameters if they are a parameter array and are on the last position
if (parameter.IsParams && isLastParameter)
{
ArrayTypeSymbol arrayType = parameter.Type as ArrayTypeSymbol;
if ((object)arrayType != null && arrayType.IsSZArray)
{
return arrayType.ElementType;
}
}
return parameter;
}
private bool HadAmbiguousWorseMethods(BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, Location location, bool isQuery, BoundExpression receiver, string name)
{
MemberResolutionResult<TMember> worseResult1;
MemberResolutionResult<TMember> worseResult2;
// UNDONE: It is unfortunate that we simply choose the first two methods as the
// UNDONE: two to say that are ambiguous; they might not actually be ambiguous
// UNDONE: with each other. We might consider building a better heuristic here.
int nWorse = TryGetFirstTwoWorseResults(out worseResult1, out worseResult2);
if (nWorse <= 1)
{
Debug.Assert(nWorse == 0, "How is it that there is exactly one applicable but worse method, and exactly zero applicable best methods? What was better than this thing?");
return false;
}
if (isQuery)
{
// Multiple implementations of the query pattern were found for source type '{0}'. Ambiguous call to '{1}'.
diagnostics.Add(ErrorCode.ERR_QueryMultipleProviders, location, receiver.Type, name);
}
else
{
// error CS0121: The call is ambiguous between the following methods or properties: 'P.W(A)' and 'P.W(B)'
diagnostics.Add(
CreateAmbiguousCallDiagnosticInfo(
worseResult1.LeastOverriddenMember.OriginalDefinition,
worseResult2.LeastOverriddenMember.OriginalDefinition,
symbols),
location);
}
return true;
}
private int TryGetFirstTwoWorseResults(out MemberResolutionResult<TMember> first, out MemberResolutionResult<TMember> second)
{
int count = 0;
bool foundFirst = false;
bool foundSecond = false;
first = default(MemberResolutionResult<TMember>);
second = default(MemberResolutionResult<TMember>);
foreach (var res in this.ResultsBuilder)
{
if (res.Result.Kind == MemberResolutionKind.Worse)
{
count++;
if (!foundFirst)
{
first = res;
foundFirst = true;
}
else if (!foundSecond)
{
second = res;
foundSecond = true;
}
}
}
return count;
}
private bool HadAmbiguousBestMethods(BindingDiagnosticBag diagnostics, ImmutableArray<Symbol> symbols, Location location)
{
MemberResolutionResult<TMember> validResult1;
MemberResolutionResult<TMember> validResult2;
var nValid = TryGetFirstTwoValidResults(out validResult1, out validResult2);
if (nValid <= 1)
{
Debug.Assert(nValid == 0, "Why are we doing error reporting on an overload resolution problem that had one valid result?");
return false;
}
// error CS0121: The call is ambiguous between the following methods or properties:
// 'P.Ambiguous(object, string)' and 'P.Ambiguous(string, object)'
diagnostics.Add(
CreateAmbiguousCallDiagnosticInfo(
validResult1.LeastOverriddenMember.OriginalDefinition,
validResult2.LeastOverriddenMember.OriginalDefinition,
symbols),
location);
return true;
}
private int TryGetFirstTwoValidResults(out MemberResolutionResult<TMember> first, out MemberResolutionResult<TMember> second)
{
int count = 0;
bool foundFirst = false;
bool foundSecond = false;
first = default(MemberResolutionResult<TMember>);
second = default(MemberResolutionResult<TMember>);
foreach (var res in this.ResultsBuilder)
{
if (res.Result.IsValid)
{
count++;
if (!foundFirst)
{
first = res;
foundFirst = true;
}
else if (!foundSecond)
{
second = res;
foundSecond = true;
}
}
}
return count;
}
private static DiagnosticInfoWithSymbols CreateAmbiguousCallDiagnosticInfo(Symbol first, Symbol second, ImmutableArray<Symbol> symbols)
{
var arguments = (first.ContainingNamespace != second.ContainingNamespace) ?
new object[]
{
new FormattedSymbol(first, SymbolDisplayFormat.CSharpErrorMessageFormat),
new FormattedSymbol(second, SymbolDisplayFormat.CSharpErrorMessageFormat)
} :
new object[]
{
first,
second
};
return new DiagnosticInfoWithSymbols(ErrorCode.ERR_AmbigCall, arguments, symbols);
}
[Conditional("DEBUG")]
private void AssertNone(MemberResolutionKind kind)
{
foreach (var result in this.ResultsBuilder)
{
if (result.Result.Kind == kind)
{
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
private MemberResolutionResult<TMember> GetFirstMemberKind(MemberResolutionKind kind)
{
foreach (var result in this.ResultsBuilder)
{
if (result.Result.Kind == kind)
{
return result;
}
}
return default(MemberResolutionResult<TMember>);
}
#if DEBUG
internal string Dump()
{
if (ResultsBuilder.Count == 0)
{
return "Overload resolution failed because the method group was empty.";
}
var sb = new StringBuilder();
if (this.Succeeded)
{
sb.AppendLine("Overload resolution succeeded and chose " + this.ValidResult.Member.ToString());
}
else if (System.Linq.Enumerable.Count(ResultsBuilder, x => x.Result.IsValid) > 1)
{
sb.AppendLine("Overload resolution failed because of ambiguous possible best methods.");
}
else if (System.Linq.Enumerable.Any(ResultsBuilder, x => (x.Result.Kind == MemberResolutionKind.TypeInferenceFailed) || (x.Result.Kind == MemberResolutionKind.TypeInferenceExtensionInstanceArgument)))
{
sb.AppendLine("Overload resolution failed (possibly) because type inference was unable to infer type parameters.");
}
sb.AppendLine("Detailed results:");
foreach (var result in ResultsBuilder)
{
sb.AppendFormat("method: {0} reason: {1}\n", result.Member.ToString(), result.Result.Kind.ToString());
}
return sb.ToString();
}
#endif
#region "Poolable"
internal static OverloadResolutionResult<TMember> GetInstance()
{
return s_pool.Allocate();
}
internal void Free()
{
this.Clear();
s_pool.Free(this);
}
//2) Expose the pool or the way to create a pool or the way to get an instance.
// for now we will expose both and figure which way works better
private static readonly ObjectPool<OverloadResolutionResult<TMember>> s_pool = CreatePool();
private static ObjectPool<OverloadResolutionResult<TMember>> CreatePool()
{
ObjectPool<OverloadResolutionResult<TMember>> pool = null;
pool = new ObjectPool<OverloadResolutionResult<TMember>>(() => new OverloadResolutionResult<TMember>(), 10);
return pool;
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Core/Diagnostics/OptionsDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class OptionsDiagnosticAnalyzer<TLanguageKindEnum> : TestDiagnosticAnalyzer<TLanguageKindEnum> where TLanguageKindEnum : struct
{
private readonly AnalyzerOptions _expectedOptions;
private readonly Dictionary<string, AnalyzerOptions> _mismatchedOptions = new Dictionary<string, AnalyzerOptions>();
public OptionsDiagnosticAnalyzer(AnalyzerOptions expectedOptions)
{
_expectedOptions = expectedOptions;
Debug.Assert(expectedOptions.AnalyzerConfigOptionsProvider.GetType() == typeof(CompilerAnalyzerConfigOptionsProvider));
}
protected override void OnAbstractMember(string AbstractMemberName, SyntaxNode node = null, ISymbol symbol = null, [CallerMemberName] string callerName = null)
{
}
protected override void OnOptions(AnalyzerOptions options, [CallerMemberName] string callerName = null)
{
if (AreEqual(options, _expectedOptions))
{
return;
}
if (_mismatchedOptions.ContainsKey(callerName))
{
_mismatchedOptions[callerName] = options;
}
else
{
_mismatchedOptions.Add(callerName, options);
}
}
private bool AreEqual(AnalyzerOptions actual, AnalyzerOptions expected)
{
if (actual.AdditionalFiles.Length != expected.AdditionalFiles.Length)
{
return false;
}
for (int i = 0; i < actual.AdditionalFiles.Length; i++)
{
if (actual.AdditionalFiles[i].Path != expected.AdditionalFiles[i].Path)
{
return false;
}
}
return true;
}
public void VerifyAnalyzerOptions()
{
Assert.True(_mismatchedOptions.Count == 0,
_mismatchedOptions.Aggregate("Mismatched calls: ", (s, m) => s + "\r\nfrom : " + m.Key + ", options :" + m.Value));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class OptionsDiagnosticAnalyzer<TLanguageKindEnum> : TestDiagnosticAnalyzer<TLanguageKindEnum> where TLanguageKindEnum : struct
{
private readonly AnalyzerOptions _expectedOptions;
private readonly Dictionary<string, AnalyzerOptions> _mismatchedOptions = new Dictionary<string, AnalyzerOptions>();
public OptionsDiagnosticAnalyzer(AnalyzerOptions expectedOptions)
{
_expectedOptions = expectedOptions;
Debug.Assert(expectedOptions.AnalyzerConfigOptionsProvider.GetType() == typeof(CompilerAnalyzerConfigOptionsProvider));
}
protected override void OnAbstractMember(string AbstractMemberName, SyntaxNode node = null, ISymbol symbol = null, [CallerMemberName] string callerName = null)
{
}
protected override void OnOptions(AnalyzerOptions options, [CallerMemberName] string callerName = null)
{
if (AreEqual(options, _expectedOptions))
{
return;
}
if (_mismatchedOptions.ContainsKey(callerName))
{
_mismatchedOptions[callerName] = options;
}
else
{
_mismatchedOptions.Add(callerName, options);
}
}
private bool AreEqual(AnalyzerOptions actual, AnalyzerOptions expected)
{
if (actual.AdditionalFiles.Length != expected.AdditionalFiles.Length)
{
return false;
}
for (int i = 0; i < actual.AdditionalFiles.Length; i++)
{
if (actual.AdditionalFiles[i].Path != expected.AdditionalFiles[i].Path)
{
return false;
}
}
return true;
}
public void VerifyAnalyzerOptions()
{
Assert.True(_mismatchedOptions.Count == 0,
_mismatchedOptions.Aggregate("Mismatched calls: ", (s, m) => s + "\r\nfrom : " + m.Key + ", options :" + m.Value));
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/NamingStyles/ManageNamingStylesDialogViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal class ManageNamingStylesDialogViewModel : AbstractNotifyPropertyChanged, IManageNamingStylesInfoDialogViewModel
{
private readonly INotificationService _notificationService;
public ObservableCollection<INamingStylesInfoDialogViewModel> Items { get; set; }
public string DialogTitle => ServicesVSResources.Manage_naming_styles;
public ManageNamingStylesDialogViewModel(
ObservableCollection<MutableNamingStyle> namingStyles,
List<NamingStyleOptionPageViewModel.NamingRuleViewModel> namingRules,
INotificationService notificationService)
{
_notificationService = notificationService;
Items = new ObservableCollection<INamingStylesInfoDialogViewModel>(namingStyles.Select(style => new NamingStyleViewModel(
style.Clone(),
!namingRules.Any(rule => rule.SelectedStyle?.ID == style.ID),
notificationService)));
}
internal void RemoveNamingStyle(NamingStyleViewModel namingStyle)
=> Items.Remove(namingStyle);
public void AddItem()
{
var style = new MutableNamingStyle();
var viewModel = new NamingStyleViewModel(style, canBeDeleted: true, notificationService: _notificationService);
var dialog = new NamingStyleDialog(viewModel);
if (dialog.ShowModal().Value == true)
{
Items.Add(viewModel);
}
}
public void RemoveItem(INamingStylesInfoDialogViewModel item)
=> Items.Remove(item);
public void EditItem(INamingStylesInfoDialogViewModel item)
{
var context = (NamingStyleViewModel)item;
var style = context.GetNamingStyle();
var viewModel = new NamingStyleViewModel(style, context.CanBeDeleted, notificationService: _notificationService);
var dialog = new NamingStyleDialog(viewModel);
if (dialog.ShowModal().Value == true)
{
context.ItemName = viewModel.ItemName;
context.RequiredPrefix = viewModel.RequiredPrefix;
context.RequiredSuffix = viewModel.RequiredSuffix;
context.WordSeparator = viewModel.WordSeparator;
context.CapitalizationSchemeIndex = viewModel.CapitalizationSchemeIndex;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal class ManageNamingStylesDialogViewModel : AbstractNotifyPropertyChanged, IManageNamingStylesInfoDialogViewModel
{
private readonly INotificationService _notificationService;
public ObservableCollection<INamingStylesInfoDialogViewModel> Items { get; set; }
public string DialogTitle => ServicesVSResources.Manage_naming_styles;
public ManageNamingStylesDialogViewModel(
ObservableCollection<MutableNamingStyle> namingStyles,
List<NamingStyleOptionPageViewModel.NamingRuleViewModel> namingRules,
INotificationService notificationService)
{
_notificationService = notificationService;
Items = new ObservableCollection<INamingStylesInfoDialogViewModel>(namingStyles.Select(style => new NamingStyleViewModel(
style.Clone(),
!namingRules.Any(rule => rule.SelectedStyle?.ID == style.ID),
notificationService)));
}
internal void RemoveNamingStyle(NamingStyleViewModel namingStyle)
=> Items.Remove(namingStyle);
public void AddItem()
{
var style = new MutableNamingStyle();
var viewModel = new NamingStyleViewModel(style, canBeDeleted: true, notificationService: _notificationService);
var dialog = new NamingStyleDialog(viewModel);
if (dialog.ShowModal().Value == true)
{
Items.Add(viewModel);
}
}
public void RemoveItem(INamingStylesInfoDialogViewModel item)
=> Items.Remove(item);
public void EditItem(INamingStylesInfoDialogViewModel item)
{
var context = (NamingStyleViewModel)item;
var style = context.GetNamingStyle();
var viewModel = new NamingStyleViewModel(style, context.CanBeDeleted, notificationService: _notificationService);
var dialog = new NamingStyleDialog(viewModel);
if (dialog.ShowModal().Value == true)
{
context.ItemName = viewModel.ItemName;
context.RequiredPrefix = viewModel.RequiredPrefix;
context.RequiredSuffix = viewModel.RequiredSuffix;
context.WordSeparator = viewModel.WordSeparator;
context.CapitalizationSchemeIndex = viewModel.CapitalizationSchemeIndex;
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/CodeModel/CodeModelEvent.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal class CodeModelEvent : IEquatable<CodeModelEvent>
{
public readonly SyntaxNode Node;
public readonly SyntaxNode ParentNode;
public CodeModelEventType Type;
public CodeModelEvent(SyntaxNode node, SyntaxNode parentNode, CodeModelEventType type)
{
this.Node = node;
this.ParentNode = parentNode;
this.Type = type;
}
public override int GetHashCode()
=> Hash.Combine(Node, Hash.Combine(ParentNode, Type.GetHashCode()));
public override bool Equals(object obj)
=> Equals(obj as CodeModelEvent);
public bool Equals(CodeModelEvent other)
{
if (other == null)
{
return false;
}
return Node == other.Node
&& ParentNode == other.ParentNode
&& Type == other.Type;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal class CodeModelEvent : IEquatable<CodeModelEvent>
{
public readonly SyntaxNode Node;
public readonly SyntaxNode ParentNode;
public CodeModelEventType Type;
public CodeModelEvent(SyntaxNode node, SyntaxNode parentNode, CodeModelEventType type)
{
this.Node = node;
this.ParentNode = parentNode;
this.Type = type;
}
public override int GetHashCode()
=> Hash.Combine(Node, Hash.Combine(ParentNode, Type.GetHashCode()));
public override bool Equals(object obj)
=> Equals(obj as CodeModelEvent);
public bool Equals(CodeModelEvent other)
{
if (other == null)
{
return false;
}
return Node == other.Node
&& ParentNode == other.ParentNode
&& Type == other.Type;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/InternalUtilities/StringTable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
#if DEBUG
using System.Diagnostics;
#endif
namespace Roslyn.Utilities
{
/// <summary>
/// This is basically a lossy cache of strings that is searchable by
/// strings, string sub ranges, character array ranges or string-builder.
/// </summary>
internal class StringTable
{
// entry in the caches
private struct Entry
{
// hash code of the entry
public int HashCode;
// full text of the item
public string Text;
}
// TODO: Need to tweak the size with more scenarios.
// for now this is what works well enough with
// Roslyn C# compiler project
// Size of local cache.
private const int LocalSizeBits = 11;
private const int LocalSize = (1 << LocalSizeBits);
private const int LocalSizeMask = LocalSize - 1;
// max size of shared cache.
private const int SharedSizeBits = 16;
private const int SharedSize = (1 << SharedSizeBits);
private const int SharedSizeMask = SharedSize - 1;
// size of bucket in shared cache. (local cache has bucket size 1).
private const int SharedBucketBits = 4;
private const int SharedBucketSize = (1 << SharedBucketBits);
private const int SharedBucketSizeMask = SharedBucketSize - 1;
// local (L1) cache
// simple fast and not threadsafe cache
// with limited size and "last add wins" expiration policy
//
// The main purpose of the local cache is to use in long lived
// single threaded operations with lots of locality (like parsing).
// Local cache is smaller (and thus faster) and is not affected
// by cache misses on other threads.
private readonly Entry[] _localTable = new Entry[LocalSize];
// shared (L2) threadsafe cache
// slightly slower than local cache
// we read this cache when having a miss in local cache
// writes to local cache will update shared cache as well.
private static readonly Entry[] s_sharedTable = new Entry[SharedSize];
// essentially a random number
// the usage pattern will randomly use and increment this
// the counter is not static to avoid interlocked operations and cross-thread traffic
private int _localRandom = Environment.TickCount;
// same as above but for users that go directly with unbuffered shared cache.
private static int s_sharedRandom = Environment.TickCount;
internal StringTable() :
this(null)
{
}
// implement Poolable object pattern
#region "Poolable"
private StringTable(ObjectPool<StringTable>? pool)
{
_pool = pool;
}
private readonly ObjectPool<StringTable>? _pool;
private static readonly ObjectPool<StringTable> s_staticPool = CreatePool();
private static ObjectPool<StringTable> CreatePool()
{
var pool = new ObjectPool<StringTable>(pool => new StringTable(pool), Environment.ProcessorCount * 2);
return pool;
}
public static StringTable GetInstance()
{
return s_staticPool.Allocate();
}
public void Free()
{
// leave cache content in the cache, just return it to the pool
// Array.Clear(this.localTable, 0, this.localTable.Length);
// Array.Clear(sharedTable, 0, sharedTable.Length);
_pool?.Free(this);
}
#endregion // Poolable
internal string Add(char[] chars, int start, int len)
{
var span = chars.AsSpan(start, len);
var hashCode = Hash.GetFNVHashCode(chars, start, len);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (StringTable.TextEquals(result, span))
{
return result;
}
}
string? shared = FindSharedEntry(chars, start, len, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, start, len, hashCode);
}
internal string Add(string chars, int start, int len)
{
var hashCode = Hash.GetFNVHashCode(chars, start, len);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (StringTable.TextEquals(result, chars, start, len))
{
return result;
}
}
string? shared = FindSharedEntry(chars, start, len, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, start, len, hashCode);
}
internal string Add(char chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null)
{
var result = arr[idx].Text;
if (text.Length == 1 && text[0] == chars)
{
return result;
}
}
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, hashCode);
}
internal string Add(StringBuilder chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (StringTable.TextEquals(result, chars))
{
return result;
}
}
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, hashCode);
}
internal string Add(string chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (result == chars)
{
return result;
}
}
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
AddCore(chars, hashCode);
return chars;
}
private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEquals(e, chars.AsSpan(start, len)))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(string chars, int start, int len, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEquals(e, chars, start, len))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan<byte> asciiChars)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEqualsASCII(e, asciiChars))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(char chars, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
if (e != null)
{
if (e.Length == 1 && e[0] == chars)
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(StringBuilder chars, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEquals(e, chars))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(string chars, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && e == chars)
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private string AddItem(char[] chars, int start, int len, int hashCode)
{
var text = new String(chars, start, len);
AddCore(text, hashCode);
return text;
}
private string AddItem(string chars, int start, int len, int hashCode)
{
var text = chars.Substring(start, len);
AddCore(text, hashCode);
return text;
}
private string AddItem(char chars, int hashCode)
{
var text = new String(chars, 1);
AddCore(text, hashCode);
return text;
}
private string AddItem(StringBuilder chars, int hashCode)
{
var text = chars.ToString();
AddCore(text, hashCode);
return text;
}
private void AddCore(string chars, int hashCode)
{
// add to the shared table first (in case someone looks for same item)
AddSharedEntry(hashCode, chars);
// add to the local table too
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
arr[idx].HashCode = hashCode;
arr[idx].Text = chars;
}
private void AddSharedEntry(int hashCode, string text)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
// try finding an empty spot in the bucket
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
int curIdx = idx;
for (int i = 1; i < SharedBucketSize + 1; i++)
{
if (arr[curIdx].Text == null)
{
idx = curIdx;
goto foundIdx;
}
curIdx = (curIdx + i) & SharedSizeMask;
}
// or pick a random victim within the bucket range
// and replace with new entry
var i1 = LocalNextRandom() & SharedBucketSizeMask;
idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask;
foundIdx:
arr[idx].HashCode = hashCode;
Volatile.Write(ref arr[idx].Text, text);
}
internal static string AddShared(StringBuilder chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
return shared;
}
return AddSharedSlow(hashCode, chars);
}
private static string AddSharedSlow(int hashCode, StringBuilder builder)
{
string text = builder.ToString();
AddSharedSlow(hashCode, text);
return text;
}
internal static string AddSharedUTF8(ReadOnlySpan<byte> bytes)
{
int hashCode = Hash.GetFNVHashCode(bytes, out bool isAscii);
if (isAscii)
{
string? shared = FindSharedEntryASCII(hashCode, bytes);
if (shared != null)
{
return shared;
}
}
return AddSharedSlow(hashCode, bytes, isAscii);
}
private static string AddSharedSlow(int hashCode, ReadOnlySpan<byte> utf8Bytes, bool isAscii)
{
string text;
unsafe
{
fixed (byte* bytes = &utf8Bytes.GetPinnableReference())
{
text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length);
}
}
// Don't add non-ascii strings to table. The hashCode we have here is not correct and we won't find them again.
// Non-ascii in UTF8-encoded parts of metadata (the only use of this at the moment) is assumed to be rare in
// practice. If that turns out to be wrong, we could decode to pooled memory and rehash here.
if (isAscii)
{
AddSharedSlow(hashCode, text);
}
return text;
}
private static void AddSharedSlow(int hashCode, string text)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
// try finding an empty spot in the bucket
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
int curIdx = idx;
for (int i = 1; i < SharedBucketSize + 1; i++)
{
if (arr[curIdx].Text == null)
{
idx = curIdx;
goto foundIdx;
}
curIdx = (curIdx + i) & SharedSizeMask;
}
// or pick a random victim within the bucket range
// and replace with new entry
var i1 = SharedNextRandom() & SharedBucketSizeMask;
idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask;
foundIdx:
arr[idx].HashCode = hashCode;
Volatile.Write(ref arr[idx].Text, text);
}
private static int LocalIdxFromHash(int hash)
{
return hash & LocalSizeMask;
}
private static int SharedIdxFromHash(int hash)
{
// we can afford to mix some more hash bits here
return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask;
}
private int LocalNextRandom()
{
return _localRandom++;
}
private static int SharedNextRandom()
{
return Interlocked.Increment(ref StringTable.s_sharedRandom);
}
internal static bool TextEquals(string array, string text, int start, int length)
{
if (array.Length != length)
{
return false;
}
// use array.Length to eliminate the range check
for (var i = 0; i < array.Length; i++)
{
if (array[i] != text[start + i])
{
return false;
}
}
return true;
}
internal static bool TextEquals(string array, StringBuilder text)
{
if (array.Length != text.Length)
{
return false;
}
// interestingly, stringbuilder holds the list of chunks by the tail
// so accessing positions at the beginning may cost more than those at the end.
for (var i = array.Length - 1; i >= 0; i--)
{
if (array[i] != text[i])
{
return false;
}
}
return true;
}
internal static bool TextEqualsASCII(string text, ReadOnlySpan<byte> ascii)
{
#if DEBUG
for (var i = 0; i < ascii.Length; i++)
{
Debug.Assert((ascii[i] & 0x80) == 0, $"The {nameof(ascii)} input to this method must be valid ASCII.");
}
#endif
if (ascii.Length != text.Length)
{
return false;
}
for (var i = 0; i < ascii.Length; i++)
{
if (ascii[i] != text[i])
{
return false;
}
}
return true;
}
internal static bool TextEquals(string array, ReadOnlySpan<char> text)
=> text.Equals(array.AsSpan(), StringComparison.Ordinal);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
#if DEBUG
using System.Diagnostics;
#endif
namespace Roslyn.Utilities
{
/// <summary>
/// This is basically a lossy cache of strings that is searchable by
/// strings, string sub ranges, character array ranges or string-builder.
/// </summary>
internal class StringTable
{
// entry in the caches
private struct Entry
{
// hash code of the entry
public int HashCode;
// full text of the item
public string Text;
}
// TODO: Need to tweak the size with more scenarios.
// for now this is what works well enough with
// Roslyn C# compiler project
// Size of local cache.
private const int LocalSizeBits = 11;
private const int LocalSize = (1 << LocalSizeBits);
private const int LocalSizeMask = LocalSize - 1;
// max size of shared cache.
private const int SharedSizeBits = 16;
private const int SharedSize = (1 << SharedSizeBits);
private const int SharedSizeMask = SharedSize - 1;
// size of bucket in shared cache. (local cache has bucket size 1).
private const int SharedBucketBits = 4;
private const int SharedBucketSize = (1 << SharedBucketBits);
private const int SharedBucketSizeMask = SharedBucketSize - 1;
// local (L1) cache
// simple fast and not threadsafe cache
// with limited size and "last add wins" expiration policy
//
// The main purpose of the local cache is to use in long lived
// single threaded operations with lots of locality (like parsing).
// Local cache is smaller (and thus faster) and is not affected
// by cache misses on other threads.
private readonly Entry[] _localTable = new Entry[LocalSize];
// shared (L2) threadsafe cache
// slightly slower than local cache
// we read this cache when having a miss in local cache
// writes to local cache will update shared cache as well.
private static readonly Entry[] s_sharedTable = new Entry[SharedSize];
// essentially a random number
// the usage pattern will randomly use and increment this
// the counter is not static to avoid interlocked operations and cross-thread traffic
private int _localRandom = Environment.TickCount;
// same as above but for users that go directly with unbuffered shared cache.
private static int s_sharedRandom = Environment.TickCount;
internal StringTable() :
this(null)
{
}
// implement Poolable object pattern
#region "Poolable"
private StringTable(ObjectPool<StringTable>? pool)
{
_pool = pool;
}
private readonly ObjectPool<StringTable>? _pool;
private static readonly ObjectPool<StringTable> s_staticPool = CreatePool();
private static ObjectPool<StringTable> CreatePool()
{
var pool = new ObjectPool<StringTable>(pool => new StringTable(pool), Environment.ProcessorCount * 2);
return pool;
}
public static StringTable GetInstance()
{
return s_staticPool.Allocate();
}
public void Free()
{
// leave cache content in the cache, just return it to the pool
// Array.Clear(this.localTable, 0, this.localTable.Length);
// Array.Clear(sharedTable, 0, sharedTable.Length);
_pool?.Free(this);
}
#endregion // Poolable
internal string Add(char[] chars, int start, int len)
{
var span = chars.AsSpan(start, len);
var hashCode = Hash.GetFNVHashCode(chars, start, len);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (StringTable.TextEquals(result, span))
{
return result;
}
}
string? shared = FindSharedEntry(chars, start, len, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, start, len, hashCode);
}
internal string Add(string chars, int start, int len)
{
var hashCode = Hash.GetFNVHashCode(chars, start, len);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (StringTable.TextEquals(result, chars, start, len))
{
return result;
}
}
string? shared = FindSharedEntry(chars, start, len, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, start, len, hashCode);
}
internal string Add(char chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null)
{
var result = arr[idx].Text;
if (text.Length == 1 && text[0] == chars)
{
return result;
}
}
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, hashCode);
}
internal string Add(StringBuilder chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (StringTable.TextEquals(result, chars))
{
return result;
}
}
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
return AddItem(chars, hashCode);
}
internal string Add(string chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
// capture array to avoid extra range checks
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
var text = arr[idx].Text;
if (text != null && arr[idx].HashCode == hashCode)
{
var result = arr[idx].Text;
if (result == chars)
{
return result;
}
}
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
// PERF: the following code does element-wise assignment of a struct
// because current JIT produces better code compared to
// arr[idx] = new Entry(...)
arr[idx].HashCode = hashCode;
arr[idx].Text = shared;
return shared;
}
AddCore(chars, hashCode);
return chars;
}
private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEquals(e, chars.AsSpan(start, len)))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(string chars, int start, int len, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEquals(e, chars, start, len))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan<byte> asciiChars)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEqualsASCII(e, asciiChars))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(char chars, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
if (e != null)
{
if (e.Length == 1 && e[0] == chars)
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(StringBuilder chars, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && TextEquals(e, chars))
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private static string? FindSharedEntry(string chars, int hashCode)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
string? e = null;
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
for (int i = 1; i < SharedBucketSize + 1; i++)
{
e = arr[idx].Text;
int hash = arr[idx].HashCode;
if (e != null)
{
if (hash == hashCode && e == chars)
{
break;
}
// this is not e we are looking for
e = null;
}
else
{
// once we see unfilled entry, the rest of the bucket will be empty
break;
}
idx = (idx + i) & SharedSizeMask;
}
return e;
}
private string AddItem(char[] chars, int start, int len, int hashCode)
{
var text = new String(chars, start, len);
AddCore(text, hashCode);
return text;
}
private string AddItem(string chars, int start, int len, int hashCode)
{
var text = chars.Substring(start, len);
AddCore(text, hashCode);
return text;
}
private string AddItem(char chars, int hashCode)
{
var text = new String(chars, 1);
AddCore(text, hashCode);
return text;
}
private string AddItem(StringBuilder chars, int hashCode)
{
var text = chars.ToString();
AddCore(text, hashCode);
return text;
}
private void AddCore(string chars, int hashCode)
{
// add to the shared table first (in case someone looks for same item)
AddSharedEntry(hashCode, chars);
// add to the local table too
var arr = _localTable;
var idx = LocalIdxFromHash(hashCode);
arr[idx].HashCode = hashCode;
arr[idx].Text = chars;
}
private void AddSharedEntry(int hashCode, string text)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
// try finding an empty spot in the bucket
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
int curIdx = idx;
for (int i = 1; i < SharedBucketSize + 1; i++)
{
if (arr[curIdx].Text == null)
{
idx = curIdx;
goto foundIdx;
}
curIdx = (curIdx + i) & SharedSizeMask;
}
// or pick a random victim within the bucket range
// and replace with new entry
var i1 = LocalNextRandom() & SharedBucketSizeMask;
idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask;
foundIdx:
arr[idx].HashCode = hashCode;
Volatile.Write(ref arr[idx].Text, text);
}
internal static string AddShared(StringBuilder chars)
{
var hashCode = Hash.GetFNVHashCode(chars);
string? shared = FindSharedEntry(chars, hashCode);
if (shared != null)
{
return shared;
}
return AddSharedSlow(hashCode, chars);
}
private static string AddSharedSlow(int hashCode, StringBuilder builder)
{
string text = builder.ToString();
AddSharedSlow(hashCode, text);
return text;
}
internal static string AddSharedUTF8(ReadOnlySpan<byte> bytes)
{
int hashCode = Hash.GetFNVHashCode(bytes, out bool isAscii);
if (isAscii)
{
string? shared = FindSharedEntryASCII(hashCode, bytes);
if (shared != null)
{
return shared;
}
}
return AddSharedSlow(hashCode, bytes, isAscii);
}
private static string AddSharedSlow(int hashCode, ReadOnlySpan<byte> utf8Bytes, bool isAscii)
{
string text;
unsafe
{
fixed (byte* bytes = &utf8Bytes.GetPinnableReference())
{
text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length);
}
}
// Don't add non-ascii strings to table. The hashCode we have here is not correct and we won't find them again.
// Non-ascii in UTF8-encoded parts of metadata (the only use of this at the moment) is assumed to be rare in
// practice. If that turns out to be wrong, we could decode to pooled memory and rehash here.
if (isAscii)
{
AddSharedSlow(hashCode, text);
}
return text;
}
private static void AddSharedSlow(int hashCode, string text)
{
var arr = s_sharedTable;
int idx = SharedIdxFromHash(hashCode);
// try finding an empty spot in the bucket
// we use quadratic probing here
// bucket positions are (n^2 + n)/2 relative to the masked hashcode
int curIdx = idx;
for (int i = 1; i < SharedBucketSize + 1; i++)
{
if (arr[curIdx].Text == null)
{
idx = curIdx;
goto foundIdx;
}
curIdx = (curIdx + i) & SharedSizeMask;
}
// or pick a random victim within the bucket range
// and replace with new entry
var i1 = SharedNextRandom() & SharedBucketSizeMask;
idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask;
foundIdx:
arr[idx].HashCode = hashCode;
Volatile.Write(ref arr[idx].Text, text);
}
private static int LocalIdxFromHash(int hash)
{
return hash & LocalSizeMask;
}
private static int SharedIdxFromHash(int hash)
{
// we can afford to mix some more hash bits here
return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask;
}
private int LocalNextRandom()
{
return _localRandom++;
}
private static int SharedNextRandom()
{
return Interlocked.Increment(ref StringTable.s_sharedRandom);
}
internal static bool TextEquals(string array, string text, int start, int length)
{
if (array.Length != length)
{
return false;
}
// use array.Length to eliminate the range check
for (var i = 0; i < array.Length; i++)
{
if (array[i] != text[start + i])
{
return false;
}
}
return true;
}
internal static bool TextEquals(string array, StringBuilder text)
{
if (array.Length != text.Length)
{
return false;
}
// interestingly, stringbuilder holds the list of chunks by the tail
// so accessing positions at the beginning may cost more than those at the end.
for (var i = array.Length - 1; i >= 0; i--)
{
if (array[i] != text[i])
{
return false;
}
}
return true;
}
internal static bool TextEqualsASCII(string text, ReadOnlySpan<byte> ascii)
{
#if DEBUG
for (var i = 0; i < ascii.Length; i++)
{
Debug.Assert((ascii[i] & 0x80) == 0, $"The {nameof(ascii)} input to this method must be valid ASCII.");
}
#endif
if (ascii.Length != text.Length)
{
return false;
}
for (var i = 0; i < ascii.Length; i++)
{
if (ascii[i] != text[i])
{
return false;
}
}
return true;
}
internal static bool TextEquals(string array, ReadOnlySpan<char> text)
=> text.Equals(array.AsSpan(), StringComparison.Ordinal);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/BoundTree/NoOpStatementFlavor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum NoOpStatementFlavor
{
Default,
// <summary>
// Marks a control yield point for emitted await operator; is processed by codegen;
// only allowed inside MoveNext methods generated for Async methods
// </summary>
AwaitYieldPoint,
// <summary>
// Marks a control resume point for emitted await operator; is processed by codegen;
// only allowed inside MoveNext methods generated for Async methods
// </summary>
AwaitResumePoint
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp
{
internal enum NoOpStatementFlavor
{
Default,
// <summary>
// Marks a control yield point for emitted await operator; is processed by codegen;
// only allowed inside MoveNext methods generated for Async methods
// </summary>
AwaitYieldPoint,
// <summary>
// Marks a control resume point for emitted await operator; is processed by codegen;
// only allowed inside MoveNext methods generated for Async methods
// </summary>
AwaitResumePoint
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Syntax/ThrowStatementSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class ThrowStatementSyntax
{
public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken)
=> Update(AttributeLists, throwKeyword, expression, semicolonToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken)
=> ThrowStatement(attributeLists: default, throwKeyword, expression, semicolonToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class ThrowStatementSyntax
{
public ThrowStatementSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken)
=> Update(AttributeLists, throwKeyword, expression, semicolonToken);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static ThrowStatementSyntax ThrowStatement(SyntaxToken throwKeyword, ExpressionSyntax expression, SyntaxToken semicolonToken)
=> ThrowStatement(attributeLists: default, throwKeyword, expression, semicolonToken);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare
{
/// <summary>
/// Handle the initialize request and report the capabilities of the server.
/// TODO Once the client side code is migrated to LSP client, this can be removed.
/// </summary>
[ExportLspRequestHandler(LiveShareConstants.RoslynLSPSDKContractName, LSP.Methods.InitializeName)]
internal class LSPSDKInitializeHandler : ILspRequestHandler<LSP.InitializeParams, LSP.InitializeResult, Solution>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LSPSDKInitializeHandler()
{
}
public Task<LSP.InitializeResult> HandleAsync(LSP.InitializeParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken)
{
var result = new LSP.InitializeResult
{
Capabilities = new LSP.ServerCapabilities()
};
return Task.FromResult(result);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare
{
/// <summary>
/// Handle the initialize request and report the capabilities of the server.
/// TODO Once the client side code is migrated to LSP client, this can be removed.
/// </summary>
[ExportLspRequestHandler(LiveShareConstants.RoslynLSPSDKContractName, LSP.Methods.InitializeName)]
internal class LSPSDKInitializeHandler : ILspRequestHandler<LSP.InitializeParams, LSP.InitializeResult, Solution>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LSPSDKInitializeHandler()
{
}
public Task<LSP.InitializeResult> HandleAsync(LSP.InitializeParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken)
{
var result = new LSP.InitializeResult
{
Capabilities = new LSP.ServerCapabilities()
};
return Task.FromResult(result);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceQueryLocal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
private static bool IsAnyQueryClause(SyntaxNode node)
=> node is QueryClauseSyntax || node is SelectOrGroupClauseSyntax;
protected override Task<Document> IntroduceQueryLocalAsync(
SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken)
{
var oldOutermostQuery = expression.GetAncestorsOrThis<QueryExpressionSyntax>().LastOrDefault();
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant: false,
containerOpt: oldOutermostQuery, cancellationToken: cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var letClause = SyntaxFactory.LetClause(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
expression).WithAdditionalAnnotations(Formatter.Annotation);
var matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken);
var innermostClauses = new HashSet<SyntaxNode>(
matches.Select(expr => expr.GetAncestorsOrThis<SyntaxNode>().First(IsAnyQueryClause)));
if (innermostClauses.Count == 1)
{
// If there was only one match, or all the matches came from the same
// statement, then we want to place the declaration right above that
// statement. Note: we special case this because the statement we are going
// to go above might not be in a block and we may have to generate it
return Task.FromResult(IntroduceQueryLocalForSingleOccurrence(
document, expression, newLocalName, letClause, allOccurrences, cancellationToken));
}
var oldInnerMostCommonQuery = matches.FindInnermostCommonNode<QueryExpressionSyntax>();
var newInnerMostQuery = Rewrite(
document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken);
var allAffectedClauses = new HashSet<SyntaxNode>(matches.SelectMany(expr => expr.GetAncestorsOrThis<SyntaxNode>().Where(IsAnyQueryClause)));
var oldClauses = oldInnerMostCommonQuery.GetAllClauses();
var newClauses = newInnerMostQuery.GetAllClauses();
var firstClauseAffectedInQuery = oldClauses.First(allAffectedClauses.Contains);
var firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery);
var finalClauses = newClauses.Take(firstClauseAffectedIndex)
.Concat(letClause)
.Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList();
var finalQuery = newInnerMostQuery.WithAllClauses(finalClauses);
var newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery);
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
private Document IntroduceQueryLocalForSingleOccurrence(
SemanticDocument document,
ExpressionSyntax expression,
NameSyntax newLocalName,
LetClauseSyntax letClause,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldClause = expression.GetAncestors<SyntaxNode>().First(IsAnyQueryClause);
var newClause = Rewrite(
document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken);
var oldQuery = (QueryBodySyntax)oldClause.Parent;
var newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause);
var newRoot = document.Root.ReplaceNode(oldQuery, newQuery);
return document.Document.WithSyntaxRoot(newRoot);
}
private static QueryBodySyntax GetNewQuery(
QueryBodySyntax oldQuery,
SyntaxNode oldClause,
SyntaxNode newClause,
LetClauseSyntax letClause)
{
var oldClauses = oldQuery.GetAllClauses();
var oldClauseIndex = oldClauses.IndexOf(oldClause);
var newClauses = oldClauses.Take(oldClauseIndex)
.Concat(letClause)
.Concat(newClause)
.Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList();
return oldQuery.WithAllClauses(newClauses);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
private static bool IsAnyQueryClause(SyntaxNode node)
=> node is QueryClauseSyntax || node is SelectOrGroupClauseSyntax;
protected override Task<Document> IntroduceQueryLocalAsync(
SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken)
{
var oldOutermostQuery = expression.GetAncestorsOrThis<QueryExpressionSyntax>().LastOrDefault();
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant: false,
containerOpt: oldOutermostQuery, cancellationToken: cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var letClause = SyntaxFactory.LetClause(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
expression).WithAdditionalAnnotations(Formatter.Annotation);
var matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken);
var innermostClauses = new HashSet<SyntaxNode>(
matches.Select(expr => expr.GetAncestorsOrThis<SyntaxNode>().First(IsAnyQueryClause)));
if (innermostClauses.Count == 1)
{
// If there was only one match, or all the matches came from the same
// statement, then we want to place the declaration right above that
// statement. Note: we special case this because the statement we are going
// to go above might not be in a block and we may have to generate it
return Task.FromResult(IntroduceQueryLocalForSingleOccurrence(
document, expression, newLocalName, letClause, allOccurrences, cancellationToken));
}
var oldInnerMostCommonQuery = matches.FindInnermostCommonNode<QueryExpressionSyntax>();
var newInnerMostQuery = Rewrite(
document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken);
var allAffectedClauses = new HashSet<SyntaxNode>(matches.SelectMany(expr => expr.GetAncestorsOrThis<SyntaxNode>().Where(IsAnyQueryClause)));
var oldClauses = oldInnerMostCommonQuery.GetAllClauses();
var newClauses = newInnerMostQuery.GetAllClauses();
var firstClauseAffectedInQuery = oldClauses.First(allAffectedClauses.Contains);
var firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery);
var finalClauses = newClauses.Take(firstClauseAffectedIndex)
.Concat(letClause)
.Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList();
var finalQuery = newInnerMostQuery.WithAllClauses(finalClauses);
var newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery);
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
private Document IntroduceQueryLocalForSingleOccurrence(
SemanticDocument document,
ExpressionSyntax expression,
NameSyntax newLocalName,
LetClauseSyntax letClause,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldClause = expression.GetAncestors<SyntaxNode>().First(IsAnyQueryClause);
var newClause = Rewrite(
document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken);
var oldQuery = (QueryBodySyntax)oldClause.Parent;
var newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause);
var newRoot = document.Root.ReplaceNode(oldQuery, newQuery);
return document.Document.WithSyntaxRoot(newRoot);
}
private static QueryBodySyntax GetNewQuery(
QueryBodySyntax oldQuery,
SyntaxNode oldClause,
SyntaxNode newClause,
LetClauseSyntax letClause)
{
var oldClauses = oldQuery.GetAllClauses();
var oldClauseIndex = oldClauses.IndexOf(oldClause);
var newClauses = oldClauses.Take(oldClauseIndex)
.Concat(letClause)
.Concat(newClause)
.Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList();
return oldQuery.WithAllClauses(newClauses);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Syntax/SkippedTokensTriviaSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public sealed partial class SkippedTokensTriviaSyntax : StructuredTriviaSyntax, ISkippedTokensTriviaSyntax
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public sealed partial class SkippedTokensTriviaSyntax : StructuredTriviaSyntax, ISkippedTokensTriviaSyntax
{
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.NumericValueSetFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
using static BinaryOperatorKind;
internal static partial class ValueSetFactory
{
/// <summary>
/// The implementation of a value set factory of any numeric type <typeparamref name="T"/>,
/// parameterized by a type class
/// <see cref="INumericTC{T}"/> that provides the primitives for that type.
/// </summary>
private sealed class NumericValueSetFactory<T, TTC> : IValueSetFactory<T> where TTC : struct, INumericTC<T>
{
public static readonly NumericValueSetFactory<T, TTC> Instance = new NumericValueSetFactory<T, TTC>();
IValueSet IValueSetFactory.AllValues => NumericValueSet<T, TTC>.AllValues;
IValueSet IValueSetFactory.NoValues => NumericValueSet<T, TTC>.NoValues;
private NumericValueSetFactory() { }
public IValueSet<T> Related(BinaryOperatorKind relation, T value)
{
TTC tc = default;
switch (relation)
{
case LessThan:
if (tc.Related(LessThanOrEqual, value, tc.MinValue))
return NumericValueSet<T, TTC>.NoValues;
return new NumericValueSet<T, TTC>(tc.MinValue, tc.Prev(value));
case LessThanOrEqual:
return new NumericValueSet<T, TTC>(tc.MinValue, value);
case GreaterThan:
if (tc.Related(GreaterThanOrEqual, value, tc.MaxValue))
return NumericValueSet<T, TTC>.NoValues;
return new NumericValueSet<T, TTC>(tc.Next(value), tc.MaxValue);
case GreaterThanOrEqual:
return new NumericValueSet<T, TTC>(value, tc.MaxValue);
case Equal:
return new NumericValueSet<T, TTC>(value, value);
default:
throw ExceptionUtilities.UnexpectedValue(relation);
}
}
IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) =>
value.IsBad ? NumericValueSet<T, TTC>.AllValues : Related(relation, default(TTC).FromConstantValue(value));
public IValueSet Random(int expectedSize, Random random) =>
NumericValueSet<T, TTC>.Random(expectedSize, random);
ConstantValue IValueSetFactory.RandomValue(Random random)
{
var tc = default(TTC);
return tc.ToConstantValue(tc.Random(random));
}
bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right)
{
var tc = default(TTC);
return tc.Related(relation, tc.FromConstantValue(left), tc.FromConstantValue(right));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
using static BinaryOperatorKind;
internal static partial class ValueSetFactory
{
/// <summary>
/// The implementation of a value set factory of any numeric type <typeparamref name="T"/>,
/// parameterized by a type class
/// <see cref="INumericTC{T}"/> that provides the primitives for that type.
/// </summary>
private sealed class NumericValueSetFactory<T, TTC> : IValueSetFactory<T> where TTC : struct, INumericTC<T>
{
public static readonly NumericValueSetFactory<T, TTC> Instance = new NumericValueSetFactory<T, TTC>();
IValueSet IValueSetFactory.AllValues => NumericValueSet<T, TTC>.AllValues;
IValueSet IValueSetFactory.NoValues => NumericValueSet<T, TTC>.NoValues;
private NumericValueSetFactory() { }
public IValueSet<T> Related(BinaryOperatorKind relation, T value)
{
TTC tc = default;
switch (relation)
{
case LessThan:
if (tc.Related(LessThanOrEqual, value, tc.MinValue))
return NumericValueSet<T, TTC>.NoValues;
return new NumericValueSet<T, TTC>(tc.MinValue, tc.Prev(value));
case LessThanOrEqual:
return new NumericValueSet<T, TTC>(tc.MinValue, value);
case GreaterThan:
if (tc.Related(GreaterThanOrEqual, value, tc.MaxValue))
return NumericValueSet<T, TTC>.NoValues;
return new NumericValueSet<T, TTC>(tc.Next(value), tc.MaxValue);
case GreaterThanOrEqual:
return new NumericValueSet<T, TTC>(value, tc.MaxValue);
case Equal:
return new NumericValueSet<T, TTC>(value, value);
default:
throw ExceptionUtilities.UnexpectedValue(relation);
}
}
IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) =>
value.IsBad ? NumericValueSet<T, TTC>.AllValues : Related(relation, default(TTC).FromConstantValue(value));
public IValueSet Random(int expectedSize, Random random) =>
NumericValueSet<T, TTC>.Random(expectedSize, random);
ConstantValue IValueSetFactory.RandomValue(Random random)
{
var tc = default(TTC);
return tc.ToConstantValue(tc.Random(random));
}
bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right)
{
var tc = default(TTC);
return tc.Related(relation, tc.FromConstantValue(left), tc.FromConstantValue(right));
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Syntax/NamespaceDeclarationSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class NamespaceDeclarationSyntax
{
internal new InternalSyntax.NamespaceDeclarationSyntax Green
{
get
{
return (InternalSyntax.NamespaceDeclarationSyntax)base.Green;
}
}
public NamespaceDeclarationSyntax Update(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken)
=> this.Update(this.AttributeLists, this.Modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class NamespaceDeclarationSyntax
{
internal new InternalSyntax.NamespaceDeclarationSyntax Green
{
get
{
return (InternalSyntax.NamespaceDeclarationSyntax)base.Green;
}
}
public NamespaceDeclarationSyntax Update(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken)
=> this.Update(this.AttributeLists, this.Modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Semantic/Semantics/BindingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingTests : CompilingTestBase
{
[Fact, WorkItem(539872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539872")]
public void NoWRN_UnreachableCode()
{
var text = @"
public class Cls
{
public static int Main()
{
goto Label2;
Label1:
return (1);
Label2:
goto Label1;
}
}";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void GenericMethodName()
{
var source =
@"class A
{
class B
{
static void M(System.Action a)
{
M(M1);
M(M2<object>);
M(M3<int>);
}
static void M1() { }
static void M2<T>() { }
}
static void M3<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeName()
{
var source =
@"class A
{
class B
{
static void M(System.Type t)
{
M(typeof(C<int>));
M(typeof(S<string, string>));
M(typeof(C<int, int>));
}
class C<T> { }
}
struct S<T, U> { }
}
class C<T, U> { }
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeParameterName()
{
var source =
@"class A<T>
{
class B<U>
{
static void M<V>()
{
N(typeof(V));
N(typeof(U));
N(typeof(T));
}
static void N(System.Type t) { }
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void WrongMethodArity()
{
var source =
@"class C
{
static void M1<T>() { }
static void M2() { }
void M3<T>() { }
void M4() { }
void M()
{
M1<object, object>();
C.M1<object, object>();
M2<int>();
C.M2<int>();
M3<object, object>();
this.M3<object, object>();
M4<int>();
this.M4<int>();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,9): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(9, 9),
// (10,11): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(10, 11),
// (11,9): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(11, 9),
// (12,11): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(12, 11),
// (13,9): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(13, 9),
// (14,14): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(14, 14),
// (15,9): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(15, 9),
// (16,14): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(16, 14));
}
[Fact]
public void AmbiguousInaccessibleMethod()
{
var source =
@"class A
{
protected void M1() { }
protected void M1(object o) { }
protected void M2(string s) { }
protected void M2(object o) { }
}
class B
{
static void M(A a)
{
a.M1();
a.M2();
M(a.M1);
M(a.M2);
}
static void M(System.Action<object> a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,11): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(12, 11),
// (13,11): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(13, 11),
// (14,13): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(14, 13),
// (15,13): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(15, 13));
}
/// <summary>
/// Should report inaccessible method, even when using
/// method as a delegate in an invalid context.
/// </summary>
[Fact]
public void InaccessibleMethodInvalidDelegateUse()
{
var source =
@"class A
{
protected object F() { return null; }
}
class B
{
static void M(A a)
{
if (a.F != null)
{
M(a.F);
a.F.ToString();
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(9, 15),
// (11,17): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(11, 17),
// (12,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(12, 15));
}
/// <summary>
/// Methods should be resolved correctly even
/// in cases where a method group is not allowed.
/// </summary>
[Fact]
public void InvalidUseOfMethodGroup()
{
var source =
@"class A
{
internal object E() { return null; }
private object F() { return null; }
}
class B
{
static void M(A a)
{
object o;
a.E += a.E;
if (a.E != null)
{
M(a.E);
a.E.ToString();
o = !a.E;
o = a.E ?? a.F;
}
a.F += a.F;
if (a.F != null)
{
M(a.F);
a.F.ToString();
o = !a.F;
o = (o != null) ? a.E : a.F;
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,9): error CS1656: Cannot assign to 'E' because it is a 'method group'
// a.E += a.E;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(11, 9),
// (14,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A'
// M(a.E);
Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(14, 15),
// (15,15): error CS0119: 'A.E()' is a method, which is not valid in the given context
// a.E.ToString();
Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(15, 15),
// (16,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group'
// o = !a.E;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "!a.E").WithArguments("!", "method group").WithLocation(16, 17),
// (17,26): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = a.E ?? a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(17, 26),
// (19,11): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 11),
// (19,18): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 18),
// (20,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// if (a.F != null)
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 15),
// (22,17): error CS0122: 'A.F()' is inaccessible due to its protection level
// M(a.F);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(22, 17),
// (23,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F.ToString();
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(23, 15),
// (24,20): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = !a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(24, 20),
// (25,39): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = (o != null) ? a.E : a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(25, 39));
}
[WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")]
[Fact(Skip = "528425")]
public void InaccessibleAndAccessible()
{
var source =
@"using System;
class A
{
void F() { }
internal void F(object o) { }
static void G() { }
internal static void G(object o) { }
void H(object o) { }
}
class B : A
{
static void M(A a)
{
a.F(null);
a.F();
A.G();
M1(a.F);
M2(a.F);
Action<object> a1 = a.F;
Action a2 = a.F;
}
void M()
{
G();
}
static void M1(Action<object> a) { }
static void M2(Action a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,11): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 11),
// (16,11): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(16, 11),
// (18,12): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action'
Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "System.Action").WithLocation(18, 12),
// (20,23): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 23),
// (24,9): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(24, 9));
}
[Fact]
public void InaccessibleAndAccessibleAndAmbiguous()
{
var source =
@"class A
{
void F(string x) { }
void F(string x, string y) { }
internal void F(object x, string y) { }
internal void F(string x, object y) { }
void G(object x, string y) { }
internal void G(string x, object y) { }
static void M(A a, string s)
{
a.F(s, s); // no error
}
}
class B
{
static void M(A a, string s, object o)
{
a.F(s, s); // accessible ambiguous
a.G(s, s); // accessible and inaccessible ambiguous, no error
a.G(o, o); // accessible and inaccessible invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'A.F(object, string)' and 'A.F(string, object)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("A.F(object, string)", "A.F(string, object)").WithLocation(18, 11),
// (20,13): error CS1503: Argument 1: cannot convert from 'object' to 'string'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "string").WithLocation(20, 13));
}
[Fact]
public void InaccessibleAndAccessibleValid()
{
var source =
@"class A
{
void F(int i) { }
internal void F(long l) { }
static void M(A a)
{
a.F(1); // no error
}
}
class B
{
static void M(A a)
{
a.F(1); // no error
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ParenthesizedDelegate()
{
var source =
@"class C
{
System.Action<object> F = null;
void M()
{
((this.F))(null);
(new C().F)(null, null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(new C().F)").WithArguments("System.Action<object>", "2").WithLocation(7, 9));
}
/// <summary>
/// Report errors for invocation expressions for non-invocable expressions,
/// and bind arguments even though invocation expression was invalid.
/// </summary>
[Fact]
public void NonMethodsWithArgs()
{
var source =
@"namespace N
{
class C<T>
{
object F;
object P { get; set; }
void M()
{
N(a);
C<string>(b);
N.C<int>(c);
N.D(d);
T(e);
(typeof(C<int>))(f);
P(g) = F(h);
this.F(i) = (this).P(j);
null.M(k);
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0103: The name 'a' does not exist in the current context
// N(a);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a"),
// (9,13): error CS0118: 'N' is a namespace but is used like a variable
// N(a);
Diagnostic(ErrorCode.ERR_BadSKknown, "N").WithArguments("N", "namespace", "variable"),
// (10,23): error CS0103: The name 'b' does not exist in the current context
// C<string>(b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b"),
// (10,13): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// C<string>(b);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<string>").WithArguments("N.C<T>"),
// (11,22): error CS0103: The name 'c' does not exist in the current context
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c"),
// (11,15): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<int>").WithArguments("N.C<T>"),
// (12,17): error CS0103: The name 'd' does not exist in the current context
// N.D(d);
Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d"),
// (12,13): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?)
// N.D(d);
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "N.D").WithArguments("D", "N"),
// (13,15): error CS0103: The name 'e' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "e").WithArguments("e"),
// (13,13): error CS0103: The name 'T' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T"),
// (14,30): error CS0103: The name 'f' does not exist in the current context
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f"),
// (14,13): error CS0149: Method name expected
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(typeof(C<int>))"),
// (15,15): error CS0103: The name 'g' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "g").WithArguments("g"),
// (15,13): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (15,22): error CS0103: The name 'h' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "h").WithArguments("h"),
// (15,20): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,20): error CS0103: The name 'i' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i"),
// (16,18): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,34): error CS0103: The name 'j' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "j").WithArguments("j"),
// (16,32): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (17,20): error CS0103: The name 'k' does not exist in the current context
// null.M(k);
Diagnostic(ErrorCode.ERR_NameNotInContext, "k").WithArguments("k"),
// (17,13): error CS0023: Operator '.' cannot be applied to operand of type '<null>'
// null.M(k);
Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M").WithArguments(".", "<null>"),
// (5,16): warning CS0649: Field 'N.C<T>.F' is never assigned to, and will always have its default value null
// object F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("N.C<T>.F", "null")
);
}
[Fact]
public void SimpleDelegates()
{
var source =
@"static class S
{
public static void F(System.Action a) { }
}
class C
{
void M()
{
S.F(this.M);
System.Action a = this.M;
S.F(a);
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void DelegatesFromOverloads()
{
var source =
@"using System;
class C
{
static void A(Action<object> a) { }
static void M(C c)
{
A(C.F);
A(c.G);
Action<object> a;
a = C.F;
a = c.G;
}
static void F() { }
static void F(object o) { }
void G(object o) { }
void G(object x, object y) { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NonViableDelegates()
{
var source =
@"using System;
class A
{
static Action F = null;
Action G = null;
}
class B
{
static void M(A a)
{
A.F(x);
a.G(y);
}
}";
CreateCompilation(source).VerifyDiagnostics( // (11,13): error CS0103: The name 'x' does not exist in the current context
// A.F(x);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"),
// (11,11): error CS0122: 'A.F' is inaccessible due to its protection level
// A.F(x);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F"),
// (12,13): error CS0103: The name 'y' does not exist in the current context
// a.G(y);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y"),
// (12,11): error CS0122: 'A.G' is inaccessible due to its protection level
// a.G(y);
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"),
// (4,19): warning CS0414: The field 'A.F' is assigned but its value is never used
// static Action F = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A.F"),
// (5,12): warning CS0414: The field 'A.G' is assigned but its value is never used
// Action G = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "G").WithArguments("A.G")
);
}
/// <summary>
/// Choose one method if overloaded methods are
/// equally invalid.
/// </summary>
[Fact]
public void ChooseOneMethodIfEquallyInvalid()
{
var source =
@"internal static class S
{
public static void M(double x, A y) { }
public static void M(double x, B y) { }
}
class A { }
class B { }
class C
{
static void M()
{
S.M(1.0, null); // ambiguous
S.M(1.0, 2.0); // equally invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'S.M(double, A)' and 'S.M(double, B)'
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("S.M(double, A)", "S.M(double, B)").WithLocation(12, 11),
// (13,18): error CS1503: Argument 2: cannot convert from 'double' to 'A'
Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "A").WithLocation(13, 18));
}
[Fact]
public void ChooseExpandedFormIfBadArgCountAndBadArgument()
{
var source =
@"class C
{
static void M(object o)
{
F();
F(o);
F(1, o);
F(1, 2, o);
}
static void F(int i, params int[] args) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'C.F(int, params int[])'
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("i", "C.F(int, params int[])").WithLocation(5, 9),
// (6,11): error CS1503: Argument 1: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "int").WithLocation(6, 11),
// (7,14): error CS1503: Argument 2: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("2", "object", "int").WithLocation(7, 14),
// (8,17): error CS1503: Argument 3: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("3", "object", "int").WithLocation(8, 17));
}
[Fact]
public void AmbiguousAndBadArgument()
{
var source =
@"class C
{
static void F(int x, double y) { }
static void F(double x, int y) { }
static void M()
{
F(1, 2);
F(1.0, 2.0);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.F(int, double)' and 'C.F(double, int)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C.F(int, double)", "C.F(double, int)").WithLocation(7, 9),
// (8,11): error CS1503: Argument 1: cannot convert from 'double' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(8, 11));
}
[WorkItem(541050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541050")]
[Fact]
public void IncompleteDelegateDecl()
{
var source =
@"namespace nms {
delegate";
CreateCompilation(source).VerifyDiagnostics(
// (3,9): error CS1031: Type expected
// delegate
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// (3,9): error CS1001: Identifier expected
// delegate
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,9): error CS1003: Syntax error, '(' expected
// delegate
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", ""),
// (3,9): error CS1026: ) expected
// delegate
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,9): error CS1002: ; expected
// delegate
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,9): error CS1513: } expected
// delegate
Diagnostic(ErrorCode.ERR_RbraceExpected, ""));
}
[WorkItem(541213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541213")]
[Fact]
public void IncompleteElsePartInIfStmt()
{
var source =
@"public class Test
{
public static int Main(string [] args)
{
if (true)
{
}
else
";
CreateCompilation(source).VerifyDiagnostics(
// (8,13): error CS1733: Expected expression
// else
Diagnostic(ErrorCode.ERR_ExpressionExpected, ""),
// (9,1): error CS1002: ; expected
//
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,23): error CS0161: 'Test.Main(string[])': not all code paths return a value
// public static int Main(string [] args)
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Test.Main(string[])")
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest01()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly1").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly1", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
int a = ClassAlias.IntField;
int b = ClassAlias.IntField;
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(7,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest02()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly2").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly2", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
ClassAlias a = new ClassAlias();
ClassAlias b = new ClassAlias();
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(6,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest03()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly3").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly3", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics(
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_Typical()
{
string scenarioCode = @"
public class ITT
: IInterfaceBase
{ }
public interface IInterfaceBase
{
void bar();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.bar()'
// : IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_FullyQualified()
{
// Using fully Qualified names
string scenarioCode = @"
public class ITT
: test.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : test.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "test.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithAlias()
{
// Using Alias
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : a1.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(5, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario01()
{
// Two interfaces, neither implemented with alias - should have 2 errors each squiggling a different interface type.
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase, a1.IInterfaceBase2
{ }
namespace test
{
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.xyz()").WithLocation(5, 7),
// (5,26): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase2.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase2").WithArguments("ITT", "test.IInterfaceBase2.xyz()").WithLocation(5, 26));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario02()
{
// Two interfaces, only the second is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase2.abc()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario03()
{
// Two interfaces, only the first is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase.xyz()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,23): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.abc()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.abc()").WithLocation(3, 23));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario04()
{
// Two interfaces, neither implemented but formatting of interfaces are on different lines
string scenarioCode = @"
public class ITT
: IInterfaceBase,
IInterfaceBase2
{ }
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase,
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7),
// (4,6): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.xyz()'
// IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.xyz()").WithLocation(4, 6));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario05()
{
// Inherited Interface scenario
// With methods not implemented in both base and derived.
// Should reflect 2 diagnostics but both with be squiggling the derived as we are not
// explicitly implementing base.
string scenarioCode = @"
public class ITT: IDerived
{ }
interface IInterfaceBase
{
void xyzb();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyzb()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IInterfaceBase.xyzb()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario06()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived, IInterfaceBase
{ }
interface IInterfaceBase
{
void xyz();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,29): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 29));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario07()
{
// Inherited Interface scenario - different order.
string scenarioCode = @"
public class ITT: IInterfaceBase, IDerived
{ }
interface IDerived : IInterfaceBase
{
void xyzd();
}
interface IInterfaceBase
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 35),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario08()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived2
{}
interface IBase
{
void method1();
}
interface IBase2
{
void Method2();
}
interface IDerived2: IBase, IBase2
{}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase.method1()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase2.Method2()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase2.Method2()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation13UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario09()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IDerived.method3()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IDerived : IBase, IBase2
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario10()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IBase3.method3()
{ }
void IDerived.method4()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2 : IBase
{
void method2();
}
public interface IBase3 : IBase
{
void method3();
}
public interface IDerived : IBase2, IBase3
{
void method4();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario11()
{
// Inherited Interface scenario
string scenarioCode = @"
static class Module1
{
public static void Main()
{
}
}
interface Ibase
{
void method1();
}
interface Ibase2
{
void method2();
}
interface Iderived : Ibase
{
void method3();
}
interface Iderived2 : Iderived
{
void method4();
}
class foo : Iderived2, Iderived, Ibase, Ibase2
{
void Ibase.method1()
{ }
void Ibase2.method2()
{ }
void Iderived2.method4()
{ }
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (29,24): error CS0535: 'foo' does not implement interface member 'Iderived.method3()'
// class foo : Iderived2, Iderived, Ibase, Ibase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Iderived").WithArguments("foo", "Iderived.method3()").WithLocation(29, 24));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass01()
{
// partial class - missing method.
// each partial implements interface but one is missing method.
string scenarioCode = @"
public partial class Foo : IBase
{
void IBase.method1()
{ }
void IBase2.method2()
{ }
}
public partial class Foo : IBase2
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (15,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(15, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass02()
{
// partial class - missing method. diagnostic is reported in correct partial class
// one partial class specifically does include any inherited interface
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (13,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(13, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass03()
{
// Partial class scenario
// One class implements multiple interfaces and is missing method.
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (9,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(9, 28)
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest04()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
int a = ClassAlias.Class1Foo();
int b = ClassAlias.Class1Foo();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (7,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int a = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (8,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int b = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
// <fine-name>(9,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest05()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
var a = new ClassAlias();
var b = new ClassAlias();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,17): error CS0143: The type 'Class1' has no constructors defined
// <fine-name>(9,17): error CS0143: The type 'Class1' has no constructors defined
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest06()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b"),
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(5,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(6,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(7,10): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest07()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
ClassAlias a = null;
ClassAlias b = null;
System.Console.WriteLine(a);
System.Console.WriteLine(b);
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (9,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(a);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (10,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(b);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"));
// NOTE: Dev10 reports NO ERRORS
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_1()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_1");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_1");
var source3 = @"
public class BarImpl : IBar
{
public ImageMoniker? Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_2()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_2");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_2");
var source3 = @"
public class BarImpl : IBar
{
ImageMoniker? IBar.Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_3()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_3");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_3");
var source3 = @"
public class BarImpl : IBar
{
public void SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_4()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_4");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_4");
var source3 = @"
public class BarImpl : IBar
{
void IBar.SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(541246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541246")]
[Fact]
public void NamespaceQualifiedGenericTypeName()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
}
class B
{
static int G = N.A<int>.F;
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NamespaceQualifiedGenericTypeNameWrongArity()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
public class B
{
public static int F;
}
public class B<T1, T2>
{
public static System.Tuple<T1, T2> F;
}
}
class C
{
static int TooMany = N.A<int, int>.F;
static int TooFew = N.A.F;
static int TooIndecisive = N.B<int>;
}";
CreateCompilation(source).VerifyDiagnostics(
// (19,28): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A<int, int>").WithArguments("N.A<T>", "type", "1"),
// (20,27): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A").WithArguments("N.A<T>", "type", "1"),
// (21,34): error CS0308: The non-generic type 'N.B' cannot be used with type arguments
//
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "B<int>").WithArguments("N.B", "type")
);
}
[WorkItem(541570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541570")]
[Fact]
public void EnumNotMemberInConstructor()
{
var source =
@"enum E { A }
class C
{
public C(E e = E.A) { }
public E E { get { return E.A; } }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(541638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541638")]
[Fact]
public void KeywordAsLabelIdentifier()
{
var source =
@"class Program
{
static void Main(string[] args)
{
@int1:
System.Console.WriteLine();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,5): warning CS0164: This label has not been referenced
//
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "@int1"));
}
[WorkItem(541677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541677")]
[Fact]
public void AssignStaticEventToLocalVariable()
{
var source =
@"delegate void Foo();
class driver
{
public static event Foo e;
static void Main(string[] args)
{
Foo x = e;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
// Note: The locations for errors on generic methods are
// name only, while Dev11 uses name + type parameters.
[WorkItem(528743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528743")]
[Fact]
public void GenericMethodLocation()
{
var source =
@"interface I
{
void M1<T>() where T : class;
}
class C : I
{
public void M1<T>() { }
void M2<T>(this object o) { }
sealed void M3<T>() { }
internal static virtual void M4<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,7): error CS1106: Extension method must be defined in a non-generic static class
// class C : I
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(5, 7),
// (7,17): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'I.M1<T>()'. Consider using an explicit interface implementation instead.
// public void M1<T>() { }
Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "I.M1<T>()").WithLocation(7, 17),
// (9,17): error CS0238: 'C.M3<T>()' cannot be sealed because it is not an override
// sealed void M3<T>() { }
Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("C.M3<T>()").WithLocation(9, 17),
// (10,34): error CS0112: A static member cannot be marked as 'virtual'
// internal static virtual void M4<T>() { }
Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M4").WithArguments("virtual").WithLocation(10, 34)
);
}
[WorkItem(542391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542391")]
[Fact]
public void PartialMethodOptionalParameters()
{
var source =
@"partial class C
{
partial void M1(object o);
partial void M1(object o = null) { }
partial void M2(object o = null);
partial void M2(object o) { }
partial void M3(object o = null);
partial void M3(object o = null) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M1(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o"),
// (8,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M3(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o")
);
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition1()
{
var source = @"
partial class C
{
partial void F(int i);
}
partial class C
{
partial void F(int j) { }
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition2()
{
var source = @"
partial class C
{
partial void F(int j) { }
}
partial class C
{
partial void F(int i);
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
/// <summary>
/// Handle a mix of parameter errors for default values,
/// partial methods, and static parameter type.
/// </summary>
[Fact]
public void ParameterErrorsDefaultPartialMethodStaticType()
{
var source =
@"static class S { }
partial class C
{
partial void M(S s = new A());
partial void M(S s = new B()) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(4, 18),
// (5,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(5, 18),
// (5,30): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(5, 30),
// (4,30): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(4, 30)
);
}
[WorkItem(543349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543349")]
[Fact]
public void Fixed()
{
var source =
@"class C
{
unsafe static void M(int[] arg)
{
fixed (int* ptr = arg) { }
fixed (int* ptr = arg) *ptr = 0;
fixed (int* ptr = arg) object o = null;
}
}";
CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,32): error CS1023: Embedded statement cannot be a declaration or labeled statement
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = null;").WithLocation(7, 32),
// (7,39): warning CS0219: The variable 'o' is assigned but its value is never used
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(7, 39)
);
}
[WorkItem(1040171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040171")]
[Fact]
public void Bug1040171()
{
const string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
foreach (string s in args)
label: c = false;
}
}
";
var compilation = CreateCompilation(sourceCode);
compilation.VerifyDiagnostics(
// (9,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label: c = false;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "label: c = false;").WithLocation(9, 13),
// (9,13): warning CS0164: This label has not been referenced
// label: c = false;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(9, 13),
// (6,14): warning CS0219: The variable 'c' is assigned but its value is never used
// bool c = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(6, 14));
}
[Fact, WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")]
private void NestedInterfaceImplementationWithOuterGenericType()
{
CompileAndVerify(@"
namespace System.ServiceModel
{
class Pipeline<T>
{
interface IStage
{
void Process(T context);
}
class AsyncStage : IStage
{
void IStage.Process(T context) { }
}
}
}");
}
/// <summary>
/// Error types should be allowed as constant types.
/// </summary>
[Fact]
public void ErrorTypeConst()
{
var source =
@"class C
{
const C1 F1 = 0;
const C2 F2 = null;
static void M()
{
const C3 c3 = 0;
const C4 c4 = null;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,11): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1").WithLocation(3, 11),
// (4,11): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C2").WithArguments("C2").WithLocation(4, 11),
// (7,15): error CS0246: The type or namespace name 'C3' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C3").WithArguments("C3").WithLocation(7, 15),
// (8,15): error CS0246: The type or namespace name 'C4' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C4").WithArguments("C4").WithLocation(8, 15));
}
[WorkItem(543777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543777")]
[Fact]
public void DefaultParameterAtEndOfFile()
{
var source =
@"class C
{
static void M(object o = null,";
CreateCompilation(source).VerifyDiagnostics(
// (3,35): error CS1031: Type expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// Cascading:
// (3,35): error CS1001: Identifier expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,35): error CS1026: ) expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,35): error CS1002: ; expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,35): error CS1513: } expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,35): error CS1737: Optional parameters must appear after all required parameters
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ""),
// (3,17): error CS0501: 'C.M(object, ?)' must declare a body because it is not
// marked abstract, extern, or partial static void M(object o = null,
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("C.M(object, ?)"));
}
[WorkItem(543814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543814")]
[Fact]
public void DuplicateNamedArgumentNullLiteral()
{
var source =
@"class C
{
static void M()
{
M("""",
arg: 0,
arg: null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS1501: No overload for method 'M' takes 3 arguments
// M("",
Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(5, 9));
}
[WorkItem(543820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543820")]
[Fact]
public void GenericAttributeClassWithMultipleParts()
{
var source =
@"class C<T> { }
class C<T> : System.Attribute { }";
CreateCompilation(source).VerifyDiagnostics(
// (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C'
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>"),
// (2,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute")
);
}
[WorkItem(543822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543822")]
[Fact]
public void InterfaceWithPartialMethodExplicitImplementation()
{
var source =
@"interface I
{
partial void I.M();
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(
// (3,20): error CS0754: A partial method may not explicitly implement an interface method
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M").WithLocation(3, 20),
// (3,20): error CS0751: A partial method must be declared within a partial type
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 20),
// (3,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.
// partial void I.M();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "M").WithArguments("default interface implementation", "8.0").WithLocation(3, 20),
// (3,18): error CS0540: 'I.M()': containing type does not implement interface 'I'
// partial void I.M();
Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("I.M()", "I").WithLocation(3, 18)
);
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructConstructor()
{
var source =
@"struct S
{
private readonly object x;
private readonly object y;
S(object x, object y)
{
try
{
this.x = x;
}
finally
{
this.y = y;
}
}
S(S o) : this(o.x, o.y) {}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructVersusTryFinally()
{
var source =
@"struct S
{
private object x;
private object y;
static void M()
{
S s1;
try { s1.x = null; } finally { s1.y = null; }
S s2 = s1;
s1.x = s1.y; s1.y = s1.x;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(544513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544513")]
[Fact()]
public void AnonTypesPropSameNameDiffType()
{
var source =
@"public class Test
{
public static void Main()
{
var p1 = new { Price = 495.00 };
var p2 = new { Price = ""36.50"" };
p1 = p2;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (8,14): error CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'AnonymousType#2'
// p1 = p2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "p2").WithArguments("<anonymous type: string Price>", "<anonymous type: double Price>"));
}
[WorkItem(545869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545869")]
[Fact]
public void TestSealedOverriddenMembers()
{
CompileAndVerify(
@"using System;
internal abstract class Base
{
public virtual int Property
{
get { return 0; }
protected set { }
}
protected virtual event EventHandler Event
{
add { } remove { }
}
protected abstract void Method();
}
internal sealed class Derived : Base
{
public override int Property
{
get { return 1; }
protected set { }
}
protected override event EventHandler Event;
protected override void Method() { }
void UseEvent() { Event(null, null); }
}
internal sealed class Derived2 : Base
{
public override int Property
{
get; protected set;
}
protected override event EventHandler Event
{
add { } remove { }
}
protected override void Method() { }
}
class Program
{
static void Main() { }
}").VerifyDiagnostics();
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_01()
{
var source =
@"
class Program
{
[System.Diagnostics.DebuggerDisplay(this)]
static void Main(string[] args)
{
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_02()
{
var source =
@"
[System.Diagnostics.DebuggerDisplay(this)]
";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact]
public void RefReturningDelegateCreation()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateCreationBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
}
[Fact]
public void RefReturningDelegateArgument()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateArgumentBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958()
{
const string source = @"
class C
{
static void Foo<T>()
{
T();
}
static void T() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,9): error CS0119: 'T' is a type, which is not valid in the given context
// T();
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9));
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958_2()
{
const string source = @"
class C
{
static void Foo<T>()
{
T<T>();
}
static void T() { }
static void T<U>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961()
{
const string source = @"
class C
{
const int T = 42;
static void Foo<T>(int x = T)
{
System.Console.Write(x);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "42");
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_2()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<T>([A(T)] int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var x = foo.Parameters[0];
var a = x.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_3()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
[A(T)]
static void Foo<T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var a = foo.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_4()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<[A(T)] T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var tt = foo.TypeParameters[0];
var a = tt.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_5()
{
const string source = @"
class C
{
class T { }
static void Foo<T>(T x = default(T))
{
System.Console.Write((object)x == null);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "True");
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_01()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
RunAction(A.B<string>.M0);
RunAction((Action)A.B<string>.M1);
}
private static void RunAction(Action action) { }
private class B<T>
{
public static void M0() { }
public static void M1() { }
}
}
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("A.B<string>.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("A.B<string>.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_02()
{
var sourceText = @"
class A
{
public delegate void MyDelegate<T>(T a);
public void Test()
{
UseMyDelegate((MyDelegate<int>)MyMethod);
UseMyDelegate((MyDelegate<long>)MyMethod);
UseMyDelegate((MyDelegate<float>)MyMethod);
UseMyDelegate((MyDelegate<double>)MyMethod);
}
private void UseMyDelegate<T>(MyDelegate<T> f) { }
private static void MyMethod(int a) { }
private static void MyMethod(long a) { }
private static void MyMethod(float a) { }
private static void MyMethod(double a) { }
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifiers = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(x => x.Identifier.ValueText.Equals("MyMethod")).ToArray();
Assert.Equal(4, identifiers.Length);
Assert.Equal("(MyDelegate<int>)MyMethod", identifiers[0].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int32 a)", model.GetSymbolInfo(identifiers[0]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<long>)MyMethod", identifiers[1].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int64 a)", model.GetSymbolInfo(identifiers[1]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<float>)MyMethod", identifiers[2].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Single a)", model.GetSymbolInfo(identifiers[2]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<double>)MyMethod", identifiers[3].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Double a)", model.GetSymbolInfo(identifiers[3]).Symbol.ToTestDisplayString());
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_03()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
var b = new A.B<string>();
RunAction(b.M0);
RunAction((Action)b.M1);
}
private static void RunAction(Action action) { }
public class B<T>
{
}
public static void M0<T>(this B<T> x) { }
public static void M1<T>(this B<T> x) { }
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("b.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0<System.String>()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("b.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1<System.String>()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(5170, "https://github.com/dotnet/roslyn/issues/5170")]
public void TypeOfBinderParameter()
{
var sourceText = @"
using System.Linq;
using System.Text;
public static class LazyToStringExtension
{
public static string LazyToString<T>(this T obj) where T : class
{
StringBuilder sb = new StringBuilder();
typeof(T)
.GetProperties(System.Reflection.BindingFlags.Public)
.Select(x => x.GetValue(obj))
}
}";
var compilation = CreateCompilationWithMscorlib40(sourceText, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (12,42): error CS1002: ; expected
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(12, 42),
// (12,28): error CS1501: No overload for method 'GetValue' takes 1 arguments
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_BadArgCount, "GetValue").WithArguments("GetValue", "1").WithLocation(12, 28),
// (7,26): error CS0161: 'LazyToStringExtension.LazyToString<T>(T)': not all code paths return a value
// public static string LazyToString<T>(this T obj) where T : class
Diagnostic(ErrorCode.ERR_ReturnExpected, "LazyToString").WithArguments("LazyToStringExtension.LazyToString<T>(T)").WithLocation(7, 26));
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = node.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
Assert.Equal("System.Reflection.PropertyInfo x", model.GetDeclaredSymbol(param).ToTestDisplayString());
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void DelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
var x = new Action<int>(i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,40): error CS1001: Identifier expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 40),
// (7,40): error CS1026: ) expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 40),
// (7,40): error CS1002: ; expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 40),
// (7,38): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void ImplicitDelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
Action<int> x = i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,32): error CS1001: Identifier expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 32),
// (7,32): error CS1002: ; expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 32),
// (7,30): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 30)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_01()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_02()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_03()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(31, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_04()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(42, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(7101, "https://github.com/dotnet/roslyn/issues/7101")]
public void UsingStatic_01()
{
var source =
@"
using System;
using static ClassWithNonStaticMethod;
using static Extension1;
class Program
{
static void Main(string[] args)
{
var instance = new Program();
instance.NonStaticMethod();
}
private void NonStaticMethod()
{
MathMin(0, 1);
MathMax(0, 1);
MathMax2(0, 1);
int x;
x = F1;
x = F2;
x.MathMax2(3);
}
}
class ClassWithNonStaticMethod
{
public static int MathMax(int a, int b)
{
return Math.Max(a, b);
}
public int MathMin(int a, int b)
{
return Math.Min(a, b);
}
public int F2 = 0;
}
static class Extension1
{
public static int MathMax2(this int a, int b)
{
return Math.Max(a, b);
}
public static int F1 = 0;
}
static class Extension2
{
public static int MathMax3(this int a, int b)
{
return Math.Max(a, b);
}
}
";
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics(
// (16,9): error CS0103: The name 'MathMin' does not exist in the current context
// MathMin(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMin").WithArguments("MathMin").WithLocation(16, 9),
// (18,9): error CS0103: The name 'MathMax2' does not exist in the current context
// MathMax2(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMax2").WithArguments("MathMax2").WithLocation(18, 9),
// (22,13): error CS0103: The name 'F2' does not exist in the current context
// x = F2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "F2").WithArguments("F2").WithLocation(22, 13)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "MathMin").Single().Parent;
Assert.Equal("MathMin(0, 1)", node1.ToString());
var names = model.LookupNames(node1.SpanStart);
Assert.False(names.Contains("MathMin"));
Assert.True(names.Contains("MathMax"));
Assert.True(names.Contains("F1"));
Assert.False(names.Contains("F2"));
Assert.False(names.Contains("MathMax2"));
Assert.False(names.Contains("MathMax3"));
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMin").IsEmpty);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "MathMax").Length);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "F1").Length);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "F2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax3").IsEmpty);
var symbols = model.LookupSymbols(node1.SpanStart);
Assert.False(symbols.Where(s => s.Name == "MathMin").Any());
Assert.True(symbols.Where(s => s.Name == "MathMax").Any());
Assert.True(symbols.Where(s => s.Name == "F1").Any());
Assert.False(symbols.Where(s => s.Name == "F2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax3").Any());
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraint()
{
var code = @"
using static Test<System.String>;
public static class Test<T> where T : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static Test<System.String>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Test<System.String>;").WithLocation(2, 1),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>'
// using static Test<System.String>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test<System.String>").WithArguments("Test<T>", "T", "string").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraintNestedType()
{
var code = @"
using static A<A<int>[]>.B;
class A<T> where T : class
{
internal static class B { }
}
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<A<int>[]>.B;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T>'
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<A<int>[]>.B").WithArguments("A<T>", "T", "int").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticMultipleGenericConstraints()
{
var code = @"
using static A<int, string>;
static class A<T, U> where T : class where U : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<int, string>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int, string>;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "T", "int").WithLocation(2, 14),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "U", "string").WithLocation(2, 14));
}
[Fact, WorkItem(8234, "https://github.com/dotnet/roslyn/issues/8234")]
public void EventAccessInTypeNameContext()
{
var source =
@"
class Program
{
static void Main() {}
event System.EventHandler E1;
void Test(Program x)
{
System.Console.WriteLine();
x.E1.E
System.Console.WriteLine();
}
void Dummy()
{
E1 = null;
var x = E1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,15): error CS1001: Identifier expected
// x.E1.E
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(11, 15),
// (11,15): error CS1002: ; expected
// x.E1.E
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15),
// (11,9): error CS0118: 'x' is a variable but is used like a type
// x.E1.E
Diagnostic(ErrorCode.ERR_BadSKknown, "x").WithArguments("x", "variable", "type").WithLocation(11, 9)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "E").Single().Parent;
Assert.Equal("x.E1.E", node1.ToString());
Assert.Equal(SyntaxKind.QualifiedName, node1.Kind());
var node2 = ((QualifiedNameSyntax)node1).Left;
Assert.Equal("x.E1", node2.ToString());
var symbolInfo2 = model.GetSymbolInfo(node2);
Assert.Null(symbolInfo2.Symbol);
Assert.Equal("event System.EventHandler Program.E1", symbolInfo2.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo2.CandidateReason);
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.True(symbolInfo1.CandidateSymbols.IsEmpty);
}
[Fact, WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")]
public void MissingTypeArgumentInGenericExtensionMethod()
{
var source =
@"
public static class FooExtensions
{
public static object ExtensionMethod0(this object obj) => default(object);
public static T ExtensionMethod1<T>(this object obj) => default(T);
public static T1 ExtensionMethod2<T1, T2>(this object obj) => default(T1);
}
public class Class1
{
public void Test()
{
var omittedArg0 = ""string literal"".ExtensionMethod0<>();
var omittedArg1 = ""string literal"".ExtensionMethod1<>();
var omittedArg2 = ""string literal"".ExtensionMethod2<>();
var omittedArgFunc0 = ""string literal"".ExtensionMethod0<>;
var omittedArgFunc1 = ""string literal"".ExtensionMethod1<>;
var omittedArgFunc2 = ""string literal"".ExtensionMethod2<>;
var moreArgs0 = ""string literal"".ExtensionMethod0<int>();
var moreArgs1 = ""string literal"".ExtensionMethod1<int, bool>();
var moreArgs2 = ""string literal"".ExtensionMethod2<int, bool, string>();
var lessArgs1 = ""string literal"".ExtensionMethod1();
var lessArgs2 = ""string literal"".ExtensionMethod2<int>();
var nonExistingMethod0 = ""string literal"".ExtensionMethodNotFound0();
var nonExistingMethod1 = ""string literal"".ExtensionMethodNotFound1<int>();
var nonExistingMethod2 = ""string literal"".ExtensionMethodNotFound2<int, string>();
System.Func<object> delegateConversion0 = ""string literal"".ExtensionMethod0<>;
System.Func<object> delegateConversion1 = ""string literal"".ExtensionMethod1<>;
System.Func<object> delegateConversion2 = ""string literal"".ExtensionMethod2<>;
var exactArgs0 = ""string literal"".ExtensionMethod0();
var exactArgs1 = ""string literal"".ExtensionMethod1<int>();
var exactArgs2 = ""string literal"".ExtensionMethod2<int, bool>();
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (13,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(13, 27),
// (13,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(13, 44),
// (14,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg1 = "string literal".ExtensionMethod1<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(14, 27),
// (15,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(15, 27),
// (15,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(15, 44),
// (17,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(17, 31),
// (17,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(17, 48),
// (18,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(18, 31),
// (18,13): error CS0815: Cannot assign method group to an implicitly-typed variable
// var omittedArgFunc1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, @"omittedArgFunc1 = ""string literal"".ExtensionMethod1<>").WithArguments("method group").WithLocation(18, 13),
// (19,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(19, 31),
// (19,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(19, 48),
// (21,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs0 = "string literal".ExtensionMethod0<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<int>").WithArguments("string", "ExtensionMethod0").WithLocation(21, 42),
// (22,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod1' and no accessible extension method 'ExtensionMethod1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs1 = "string literal".ExtensionMethod1<int, bool>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod1<int, bool>").WithArguments("string", "ExtensionMethod1").WithLocation(22, 42),
// (23,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs2 = "string literal".ExtensionMethod2<int, bool, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int, bool, string>").WithArguments("string", "ExtensionMethod2").WithLocation(23, 42),
// (25,42): error CS0411: The type arguments for method 'FooExtensions.ExtensionMethod1<T>(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// var lessArgs1 = "string literal".ExtensionMethod1();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "ExtensionMethod1").WithArguments("FooExtensions.ExtensionMethod1<T>(object)").WithLocation(25, 42),
// (26,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var lessArgs2 = "string literal".ExtensionMethod2<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int>").WithArguments("string", "ExtensionMethod2").WithLocation(26, 42),
// (28,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound0' and no accessible extension method 'ExtensionMethodNotFound0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod0 = "string literal".ExtensionMethodNotFound0();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound0").WithArguments("string", "ExtensionMethodNotFound0").WithLocation(28, 51),
// (29,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound1' and no accessible extension method 'ExtensionMethodNotFound1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod1 = "string literal".ExtensionMethodNotFound1<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound1<int>").WithArguments("string", "ExtensionMethodNotFound1").WithLocation(29, 51),
// (30,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound2' and no accessible extension method 'ExtensionMethodNotFound2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod2 = "string literal".ExtensionMethodNotFound2<int, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound2<int, string>").WithArguments("string", "ExtensionMethodNotFound2").WithLocation(30, 51),
// (32,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(32, 51),
// (32,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(32, 68),
// (33,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(33, 51),
// (33,51): error CS0407: '? FooExtensions.ExtensionMethod1<?>(object)' has the wrong return type
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_BadRetType, @"""string literal"".ExtensionMethod1<>").WithArguments("FooExtensions.ExtensionMethod1<?>(object)", "?").WithLocation(33, 51),
// (34,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(34, 51),
// (34,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(34, 68));
}
[WorkItem(22757, "https://github.com/dotnet/roslyn/issues/22757")]
[Fact]
public void MethodGroupConversionNoReceiver()
{
var source =
@"using System;
using System.Collections.Generic;
class A
{
class B
{
void F()
{
IEnumerable<string> c = null;
c.S(G);
}
}
object G(string s)
{
return null;
}
}
static class E
{
internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f)
{
throw new NotImplementedException();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (10,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)'
// c.S(G);
Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(10, 17));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "G").First();
var info = model.GetSymbolInfo(node);
Assert.Equal("System.Object A.G(System.String s)", info.Symbol.ToTestDisplayString());
}
[Fact]
public void BindingLambdaArguments_DuplicateNamedArguments()
{
var compilation = CreateCompilation(@"
using System;
class X
{
void M<T>(T arg1, Func<T, T> arg2)
{
}
void N()
{
M(arg1: 5, arg2: x => x, arg2: y => y);
}
}").VerifyDiagnostics(
// (10,34): error CS1740: Named argument 'arg2' cannot be specified multiple times
// M(arg1: 5, arg2: x => 0, arg2: y => 0);
Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "arg2").WithArguments("arg2").WithLocation(10, 34));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var lambda = tree.GetRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(s => s.Parameter.Identifier.Text == "x");
var typeInfo = model.GetTypeInfo(lambda.Body);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class BindingTests : CompilingTestBase
{
[Fact, WorkItem(539872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539872")]
public void NoWRN_UnreachableCode()
{
var text = @"
public class Cls
{
public static int Main()
{
goto Label2;
Label1:
return (1);
Label2:
goto Label1;
}
}";
CreateCompilation(text).VerifyDiagnostics();
}
[Fact]
public void GenericMethodName()
{
var source =
@"class A
{
class B
{
static void M(System.Action a)
{
M(M1);
M(M2<object>);
M(M3<int>);
}
static void M1() { }
static void M2<T>() { }
}
static void M3<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeName()
{
var source =
@"class A
{
class B
{
static void M(System.Type t)
{
M(typeof(C<int>));
M(typeof(S<string, string>));
M(typeof(C<int, int>));
}
class C<T> { }
}
struct S<T, U> { }
}
class C<T, U> { }
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void GenericTypeParameterName()
{
var source =
@"class A<T>
{
class B<U>
{
static void M<V>()
{
N(typeof(V));
N(typeof(U));
N(typeof(T));
}
static void N(System.Type t) { }
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void WrongMethodArity()
{
var source =
@"class C
{
static void M1<T>() { }
static void M2() { }
void M3<T>() { }
void M4() { }
void M()
{
M1<object, object>();
C.M1<object, object>();
M2<int>();
C.M2<int>();
M3<object, object>();
this.M3<object, object>();
M4<int>();
this.M4<int>();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,9): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(9, 9),
// (10,11): error CS0305: Using the generic method 'C.M1<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M1<object, object>").WithArguments("C.M1<T>()", "method", "1").WithLocation(10, 11),
// (11,9): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(11, 9),
// (12,11): error CS0308: The non-generic method 'C.M2()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M2<int>").WithArguments("C.M2()", "method").WithLocation(12, 11),
// (13,9): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(13, 9),
// (14,14): error CS0305: Using the generic method 'C.M3<T>()' requires 1 type arguments
Diagnostic(ErrorCode.ERR_BadArity, "M3<object, object>").WithArguments("C.M3<T>()", "method", "1").WithLocation(14, 14),
// (15,9): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(15, 9),
// (16,14): error CS0308: The non-generic method 'C.M4()' cannot be used with type arguments
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M4<int>").WithArguments("C.M4()", "method").WithLocation(16, 14));
}
[Fact]
public void AmbiguousInaccessibleMethod()
{
var source =
@"class A
{
protected void M1() { }
protected void M1(object o) { }
protected void M2(string s) { }
protected void M2(object o) { }
}
class B
{
static void M(A a)
{
a.M1();
a.M2();
M(a.M1);
M(a.M2);
}
static void M(System.Action<object> a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,11): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(12, 11),
// (13,11): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(13, 11),
// (14,13): error CS0122: 'A.M1()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M1").WithArguments("A.M1()").WithLocation(14, 13),
// (15,13): error CS0122: 'A.M2(string)' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "M2").WithArguments("A.M2(string)").WithLocation(15, 13));
}
/// <summary>
/// Should report inaccessible method, even when using
/// method as a delegate in an invalid context.
/// </summary>
[Fact]
public void InaccessibleMethodInvalidDelegateUse()
{
var source =
@"class A
{
protected object F() { return null; }
}
class B
{
static void M(A a)
{
if (a.F != null)
{
M(a.F);
a.F.ToString();
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(9, 15),
// (11,17): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(11, 17),
// (12,15): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(12, 15));
}
/// <summary>
/// Methods should be resolved correctly even
/// in cases where a method group is not allowed.
/// </summary>
[Fact]
public void InvalidUseOfMethodGroup()
{
var source =
@"class A
{
internal object E() { return null; }
private object F() { return null; }
}
class B
{
static void M(A a)
{
object o;
a.E += a.E;
if (a.E != null)
{
M(a.E);
a.E.ToString();
o = !a.E;
o = a.E ?? a.F;
}
a.F += a.F;
if (a.F != null)
{
M(a.F);
a.F.ToString();
o = !a.F;
o = (o != null) ? a.E : a.F;
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,9): error CS1656: Cannot assign to 'E' because it is a 'method group'
// a.E += a.E;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(11, 9),
// (14,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A'
// M(a.E);
Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(14, 15),
// (15,15): error CS0119: 'A.E()' is a method, which is not valid in the given context
// a.E.ToString();
Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(15, 15),
// (16,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group'
// o = !a.E;
Diagnostic(ErrorCode.ERR_BadUnaryOp, "!a.E").WithArguments("!", "method group").WithLocation(16, 17),
// (17,26): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = a.E ?? a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(17, 26),
// (19,11): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 11),
// (19,18): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F += a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(19, 18),
// (20,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// if (a.F != null)
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 15),
// (22,17): error CS0122: 'A.F()' is inaccessible due to its protection level
// M(a.F);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(22, 17),
// (23,15): error CS0122: 'A.F()' is inaccessible due to its protection level
// a.F.ToString();
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(23, 15),
// (24,20): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = !a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(24, 20),
// (25,39): error CS0122: 'A.F()' is inaccessible due to its protection level
// o = (o != null) ? a.E : a.F;
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(25, 39));
}
[WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")]
[Fact(Skip = "528425")]
public void InaccessibleAndAccessible()
{
var source =
@"using System;
class A
{
void F() { }
internal void F(object o) { }
static void G() { }
internal static void G(object o) { }
void H(object o) { }
}
class B : A
{
static void M(A a)
{
a.F(null);
a.F();
A.G();
M1(a.F);
M2(a.F);
Action<object> a1 = a.F;
Action a2 = a.F;
}
void M()
{
G();
}
static void M1(Action<object> a) { }
static void M2(Action a) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,11): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(15, 11),
// (16,11): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(16, 11),
// (18,12): error CS1503: Argument 1: cannot convert from 'method group' to 'System.Action'
Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "System.Action").WithLocation(18, 12),
// (20,23): error CS0122: 'A.F()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F()").WithLocation(20, 23),
// (24,9): error CS0122: 'A.G()' is inaccessible due to its protection level
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G()").WithLocation(24, 9));
}
[Fact]
public void InaccessibleAndAccessibleAndAmbiguous()
{
var source =
@"class A
{
void F(string x) { }
void F(string x, string y) { }
internal void F(object x, string y) { }
internal void F(string x, object y) { }
void G(object x, string y) { }
internal void G(string x, object y) { }
static void M(A a, string s)
{
a.F(s, s); // no error
}
}
class B
{
static void M(A a, string s, object o)
{
a.F(s, s); // accessible ambiguous
a.G(s, s); // accessible and inaccessible ambiguous, no error
a.G(o, o); // accessible and inaccessible invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'A.F(object, string)' and 'A.F(string, object)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("A.F(object, string)", "A.F(string, object)").WithLocation(18, 11),
// (20,13): error CS1503: Argument 1: cannot convert from 'object' to 'string'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "string").WithLocation(20, 13));
}
[Fact]
public void InaccessibleAndAccessibleValid()
{
var source =
@"class A
{
void F(int i) { }
internal void F(long l) { }
static void M(A a)
{
a.F(1); // no error
}
}
class B
{
static void M(A a)
{
a.F(1); // no error
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void ParenthesizedDelegate()
{
var source =
@"class C
{
System.Action<object> F = null;
void M()
{
((this.F))(null);
(new C().F)(null, null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(new C().F)").WithArguments("System.Action<object>", "2").WithLocation(7, 9));
}
/// <summary>
/// Report errors for invocation expressions for non-invocable expressions,
/// and bind arguments even though invocation expression was invalid.
/// </summary>
[Fact]
public void NonMethodsWithArgs()
{
var source =
@"namespace N
{
class C<T>
{
object F;
object P { get; set; }
void M()
{
N(a);
C<string>(b);
N.C<int>(c);
N.D(d);
T(e);
(typeof(C<int>))(f);
P(g) = F(h);
this.F(i) = (this).P(j);
null.M(k);
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,15): error CS0103: The name 'a' does not exist in the current context
// N(a);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a"),
// (9,13): error CS0118: 'N' is a namespace but is used like a variable
// N(a);
Diagnostic(ErrorCode.ERR_BadSKknown, "N").WithArguments("N", "namespace", "variable"),
// (10,23): error CS0103: The name 'b' does not exist in the current context
// C<string>(b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b"),
// (10,13): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// C<string>(b);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<string>").WithArguments("N.C<T>"),
// (11,22): error CS0103: The name 'c' does not exist in the current context
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c"),
// (11,15): error CS1955: Non-invocable member 'N.C<T>' cannot be used like a method.
// N.C<int>(c);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "C<int>").WithArguments("N.C<T>"),
// (12,17): error CS0103: The name 'd' does not exist in the current context
// N.D(d);
Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d"),
// (12,13): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?)
// N.D(d);
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "N.D").WithArguments("D", "N"),
// (13,15): error CS0103: The name 'e' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "e").WithArguments("e"),
// (13,13): error CS0103: The name 'T' does not exist in the current context
// T(e);
Diagnostic(ErrorCode.ERR_NameNotInContext, "T").WithArguments("T"),
// (14,30): error CS0103: The name 'f' does not exist in the current context
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f"),
// (14,13): error CS0149: Method name expected
// (typeof(C<int>))(f);
Diagnostic(ErrorCode.ERR_MethodNameExpected, "(typeof(C<int>))"),
// (15,15): error CS0103: The name 'g' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "g").WithArguments("g"),
// (15,13): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (15,22): error CS0103: The name 'h' does not exist in the current context
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NameNotInContext, "h").WithArguments("h"),
// (15,20): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// P(g) = F(h);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,20): error CS0103: The name 'i' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i"),
// (16,18): error CS1955: Non-invocable member 'N.C<T>.F' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "F").WithArguments("N.C<T>.F"),
// (16,34): error CS0103: The name 'j' does not exist in the current context
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NameNotInContext, "j").WithArguments("j"),
// (16,32): error CS1955: Non-invocable member 'N.C<T>.P' cannot be used like a method.
// this.F(i) = (this).P(j);
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "P").WithArguments("N.C<T>.P"),
// (17,20): error CS0103: The name 'k' does not exist in the current context
// null.M(k);
Diagnostic(ErrorCode.ERR_NameNotInContext, "k").WithArguments("k"),
// (17,13): error CS0023: Operator '.' cannot be applied to operand of type '<null>'
// null.M(k);
Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.M").WithArguments(".", "<null>"),
// (5,16): warning CS0649: Field 'N.C<T>.F' is never assigned to, and will always have its default value null
// object F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("N.C<T>.F", "null")
);
}
[Fact]
public void SimpleDelegates()
{
var source =
@"static class S
{
public static void F(System.Action a) { }
}
class C
{
void M()
{
S.F(this.M);
System.Action a = this.M;
S.F(a);
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void DelegatesFromOverloads()
{
var source =
@"using System;
class C
{
static void A(Action<object> a) { }
static void M(C c)
{
A(C.F);
A(c.G);
Action<object> a;
a = C.F;
a = c.G;
}
static void F() { }
static void F(object o) { }
void G(object o) { }
void G(object x, object y) { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NonViableDelegates()
{
var source =
@"using System;
class A
{
static Action F = null;
Action G = null;
}
class B
{
static void M(A a)
{
A.F(x);
a.G(y);
}
}";
CreateCompilation(source).VerifyDiagnostics( // (11,13): error CS0103: The name 'x' does not exist in the current context
// A.F(x);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"),
// (11,11): error CS0122: 'A.F' is inaccessible due to its protection level
// A.F(x);
Diagnostic(ErrorCode.ERR_BadAccess, "F").WithArguments("A.F"),
// (12,13): error CS0103: The name 'y' does not exist in the current context
// a.G(y);
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y"),
// (12,11): error CS0122: 'A.G' is inaccessible due to its protection level
// a.G(y);
Diagnostic(ErrorCode.ERR_BadAccess, "G").WithArguments("A.G"),
// (4,19): warning CS0414: The field 'A.F' is assigned but its value is never used
// static Action F = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A.F"),
// (5,12): warning CS0414: The field 'A.G' is assigned but its value is never used
// Action G = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "G").WithArguments("A.G")
);
}
/// <summary>
/// Choose one method if overloaded methods are
/// equally invalid.
/// </summary>
[Fact]
public void ChooseOneMethodIfEquallyInvalid()
{
var source =
@"internal static class S
{
public static void M(double x, A y) { }
public static void M(double x, B y) { }
}
class A { }
class B { }
class C
{
static void M()
{
S.M(1.0, null); // ambiguous
S.M(1.0, 2.0); // equally invalid
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'S.M(double, A)' and 'S.M(double, B)'
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("S.M(double, A)", "S.M(double, B)").WithLocation(12, 11),
// (13,18): error CS1503: Argument 2: cannot convert from 'double' to 'A'
Diagnostic(ErrorCode.ERR_BadArgType, "2.0").WithArguments("2", "double", "A").WithLocation(13, 18));
}
[Fact]
public void ChooseExpandedFormIfBadArgCountAndBadArgument()
{
var source =
@"class C
{
static void M(object o)
{
F();
F(o);
F(1, o);
F(1, 2, o);
}
static void F(int i, params int[] args) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'C.F(int, params int[])'
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("i", "C.F(int, params int[])").WithLocation(5, 9),
// (6,11): error CS1503: Argument 1: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("1", "object", "int").WithLocation(6, 11),
// (7,14): error CS1503: Argument 2: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("2", "object", "int").WithLocation(7, 14),
// (8,17): error CS1503: Argument 3: cannot convert from 'object' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "o").WithArguments("3", "object", "int").WithLocation(8, 17));
}
[Fact]
public void AmbiguousAndBadArgument()
{
var source =
@"class C
{
static void F(int x, double y) { }
static void F(double x, int y) { }
static void M()
{
F(1, 2);
F(1.0, 2.0);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.F(int, double)' and 'C.F(double, int)'
Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("C.F(int, double)", "C.F(double, int)").WithLocation(7, 9),
// (8,11): error CS1503: Argument 1: cannot convert from 'double' to 'int'
Diagnostic(ErrorCode.ERR_BadArgType, "1.0").WithArguments("1", "double", "int").WithLocation(8, 11));
}
[WorkItem(541050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541050")]
[Fact]
public void IncompleteDelegateDecl()
{
var source =
@"namespace nms {
delegate";
CreateCompilation(source).VerifyDiagnostics(
// (3,9): error CS1031: Type expected
// delegate
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// (3,9): error CS1001: Identifier expected
// delegate
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,9): error CS1003: Syntax error, '(' expected
// delegate
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", ""),
// (3,9): error CS1026: ) expected
// delegate
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,9): error CS1002: ; expected
// delegate
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,9): error CS1513: } expected
// delegate
Diagnostic(ErrorCode.ERR_RbraceExpected, ""));
}
[WorkItem(541213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541213")]
[Fact]
public void IncompleteElsePartInIfStmt()
{
var source =
@"public class Test
{
public static int Main(string [] args)
{
if (true)
{
}
else
";
CreateCompilation(source).VerifyDiagnostics(
// (8,13): error CS1733: Expected expression
// else
Diagnostic(ErrorCode.ERR_ExpressionExpected, ""),
// (9,1): error CS1002: ; expected
//
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (9,1): error CS1513: } expected
//
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,23): error CS0161: 'Test.Main(string[])': not all code paths return a value
// public static int Main(string [] args)
Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("Test.Main(string[])")
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest01()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly1").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly1", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
int a = ClassAlias.IntField;
int b = ClassAlias.IntField;
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(7,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest02()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly2").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly2", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
static void Main()
{
ClassAlias a = new ClassAlias();
ClassAlias b = new ClassAlias();
}
}
", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics();
// NOTE: Dev10 errors:
// <fine-name>(6,9): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest03()
{
var baseAssembly = CreateCompilation(
@"
namespace BaseAssembly {
public class BaseClass {
}
}
", assemblyName: "BaseAssembly3").VerifyDiagnostics();
var derivedAssembly = CreateCompilation(
@"
namespace DerivedAssembly {
public class DerivedClass: BaseAssembly.BaseClass {
public static int IntField = 123;
}
}
", assemblyName: "DerivedAssembly3", references: new List<MetadataReference>() { baseAssembly.EmitToImageReference() }).VerifyDiagnostics();
var testAssembly = CreateCompilation(
@"
using ClassAlias = DerivedAssembly.DerivedClass;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { derivedAssembly.EmitToImageReference() })
.VerifyDiagnostics(
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS0012: The type 'BaseAssembly.BaseClass' is defined in an assembly that is not referenced. You must add a reference to assembly 'BaseAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_Typical()
{
string scenarioCode = @"
public class ITT
: IInterfaceBase
{ }
public interface IInterfaceBase
{
void bar();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.bar()'
// : IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_FullyQualified()
{
// Using fully Qualified names
string scenarioCode = @"
public class ITT
: test.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : test.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "test.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithAlias()
{
// Using Alias
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase
{ }
namespace test
{
public interface IInterfaceBase
{
void bar();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.bar()'
// : a1.IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.bar()").WithLocation(5, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario01()
{
// Two interfaces, neither implemented with alias - should have 2 errors each squiggling a different interface type.
string scenarioCode = @"
using a1 = test;
public class ITT
: a1.IInterfaceBase, a1.IInterfaceBase2
{ }
namespace test
{
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (5,7): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase").WithArguments("ITT", "test.IInterfaceBase.xyz()").WithLocation(5, 7),
// (5,26): error CS0535: 'ITT' does not implement interface member 'test.IInterfaceBase2.xyz()'
// : a1.IInterfaceBase, a1.IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "a1.IInterfaceBase2").WithArguments("ITT", "test.IInterfaceBase2.xyz()").WithLocation(5, 26));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario02()
{
// Two interfaces, only the second is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase2.abc()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario03()
{
// Two interfaces, only the first is implemented
string scenarioCode = @"
public class ITT
: IInterfaceBase, IInterfaceBase2
{
void IInterfaceBase.xyz()
{ }
}
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void abc();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,23): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.abc()'
// : IInterfaceBase, IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.abc()").WithLocation(3, 23));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario04()
{
// Two interfaces, neither implemented but formatting of interfaces are on different lines
string scenarioCode = @"
public class ITT
: IInterfaceBase,
IInterfaceBase2
{ }
public interface IInterfaceBase
{
void xyz();
}
public interface IInterfaceBase2
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (3,7): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// : IInterfaceBase,
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(3, 7),
// (4,6): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase2.xyz()'
// IInterfaceBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase2").WithArguments("ITT", "IInterfaceBase2.xyz()").WithLocation(4, 6));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario05()
{
// Inherited Interface scenario
// With methods not implemented in both base and derived.
// Should reflect 2 diagnostics but both with be squiggling the derived as we are not
// explicitly implementing base.
string scenarioCode = @"
public class ITT: IDerived
{ }
interface IInterfaceBase
{
void xyzb();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyzb()'
// public class ITT: IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IInterfaceBase.xyzb()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario06()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived, IInterfaceBase
{ }
interface IInterfaceBase
{
void xyz();
}
interface IDerived : IInterfaceBase
{
void xyzd();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 19),
// (2,29): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IDerived, IInterfaceBase
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 29));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario07()
{
// Inherited Interface scenario - different order.
string scenarioCode = @"
public class ITT: IInterfaceBase, IDerived
{ }
interface IDerived : IInterfaceBase
{
void xyzd();
}
interface IInterfaceBase
{
void xyz();
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'ITT' does not implement interface member 'IDerived.xyzd()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IDerived.xyzd()").WithLocation(2, 35),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IInterfaceBase.xyz()'
// public class ITT: IInterfaceBase, IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IInterfaceBase").WithArguments("ITT", "IInterfaceBase.xyz()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario08()
{
// Inherited Interface scenario
string scenarioCode = @"
public class ITT: IDerived2
{}
interface IBase
{
void method1();
}
interface IBase2
{
void Method2();
}
interface IDerived2: IBase, IBase2
{}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase.method1()").WithLocation(2, 19),
// (2,19): error CS0535: 'ITT' does not implement interface member 'IBase2.Method2()'
// public class ITT: IDerived2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived2").WithArguments("ITT", "IBase2.Method2()").WithLocation(2, 19));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation13UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario09()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IDerived.method3()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IDerived : IBase, IBase2
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario10()
{
// Inherited Interface scenario.
string scenarioCode = @"
public class ITT : IDerived
{
void IBase2.method2()
{ }
void IBase3.method3()
{ }
void IDerived.method4()
{ }
}
public interface IBase
{
void method1();
}
public interface IBase2 : IBase
{
void method2();
}
public interface IBase3 : IBase
{
void method3();
}
public interface IDerived : IBase2, IBase3
{
void method4();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,20): error CS0535: 'ITT' does not implement interface member 'IBase.method1()'
// public class ITT : IDerived
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IDerived").WithArguments("ITT", "IBase.method1()").WithLocation(2, 20));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_InterfaceInheritanceScenario11()
{
// Inherited Interface scenario
string scenarioCode = @"
static class Module1
{
public static void Main()
{
}
}
interface Ibase
{
void method1();
}
interface Ibase2
{
void method2();
}
interface Iderived : Ibase
{
void method3();
}
interface Iderived2 : Iderived
{
void method4();
}
class foo : Iderived2, Iderived, Ibase, Ibase2
{
void Ibase.method1()
{ }
void Ibase2.method2()
{ }
void Iderived2.method4()
{ }
}
";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (29,24): error CS0535: 'foo' does not implement interface member 'Iderived.method3()'
// class foo : Iderived2, Iderived, Ibase, Ibase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Iderived").WithArguments("foo", "Iderived.method3()").WithLocation(29, 24));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass01()
{
// partial class - missing method.
// each partial implements interface but one is missing method.
string scenarioCode = @"
public partial class Foo : IBase
{
void IBase.method1()
{ }
void IBase2.method2()
{ }
}
public partial class Foo : IBase2
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (15,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(15, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass02()
{
// partial class - missing method. diagnostic is reported in correct partial class
// one partial class specifically does include any inherited interface
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo
{
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (13,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(13, 28));
}
[WorkItem(911913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/911913")]
[Fact]
public void UnimplementedInterfaceSquiggleLocation_WithPartialClass03()
{
// Partial class scenario
// One class implements multiple interfaces and is missing method.
string scenarioCode = @"
public partial class Foo : IBase, IBase2
{
void IBase.method1()
{ }
}
public partial class Foo : IBase3
{
}
public interface IBase
{
void method1();
}
public interface IBase2
{
void method2();
}
public interface IBase3
{
void method3();
}";
var testAssembly = CreateCompilation(scenarioCode);
testAssembly.VerifyDiagnostics(
// (2,35): error CS0535: 'Foo' does not implement interface member 'IBase2.method2()'
// public partial class Foo : IBase, IBase2
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase2").WithArguments("Foo", "IBase2.method2()").WithLocation(2, 35),
// (9,28): error CS0535: 'Foo' does not implement interface member 'IBase3.method3()'
// public partial class Foo : IBase3
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IBase3").WithArguments("Foo", "IBase3.method3()").WithLocation(9, 28)
);
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest04()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
int a = ClassAlias.Class1Foo();
int b = ClassAlias.Class1Foo();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (7,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int a = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (8,28): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// int b = ClassAlias.Class1Foo();
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1Foo").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
// <fine-name>(9,28): error CS0117: 'Class1' does not contain a definition for 'Class1Foo'
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest05()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
var a = new ClassAlias();
var b = new ClassAlias();
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")
);
// NOTE: Dev10 errors:
// <fine-name>(8,17): error CS0143: The type 'Class1' has no constructors defined
// <fine-name>(9,17): error CS0143: The type 'Class1' has no constructors defined
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest06()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
ClassAlias a = null;
ClassAlias b = null;
ClassAlias m() { return null; }
void m2(ClassAlias p) { }
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (6,16): warning CS0414: The field 'Test.b' is assigned but its value is never used
// ClassAlias b = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("Test.b"),
// (5,16): warning CS0414: The field 'Test.a' is assigned but its value is never used
// ClassAlias a = null;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("Test.a")
);
// NOTE: Dev10 errors:
// <fine-name>(4,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(5,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(6,16): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
// <fine-name>(7,10): error CS1772: Type 'Class1' from assembly '...\NoPIAGenerics1-Asm1.dll' cannot be used across assembly boundaries because a type in its inheritance hierarchy has a generic type parameter that is an embedded interop type.
}
[WorkItem(541466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541466")]
[Fact]
public void UseSiteErrorViaAliasTest07()
{
var testAssembly = CreateCompilation(
@"
using ClassAlias = Class1;
public class Test
{
void m()
{
ClassAlias a = null;
ClassAlias b = null;
System.Console.WriteLine(a);
System.Console.WriteLine(b);
}
}", references: new List<MetadataReference>() { TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1 })
.VerifyDiagnostics(
// (2,20): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// using ClassAlias = Class1;
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "Class1").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (9,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(a);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
// (10,9): error CS1769: Type 'System.Collections.Generic.List<FooStruct>' from assembly 'NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// System.Console.WriteLine(b);
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "System.Console.WriteLine").WithArguments("System.Collections.Generic.List<FooStruct>", "NoPIAGenerics1-Asm1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"));
// NOTE: Dev10 reports NO ERRORS
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_1()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_1");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_1");
var source3 = @"
public class BarImpl : IBar
{
public ImageMoniker? Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_2()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_2");
var source2 = @"
public interface IBar
{
ImageMoniker? Moniker { get; }
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_2");
var source3 = @"
public class BarImpl : IBar
{
ImageMoniker? IBar.Moniker
{
get { return null; }
}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,24): error CS0539: 'BarImpl.Moniker' in explicit interface declaration is not a member of interface
// ImageMoniker? IBar.Moniker
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Moniker").WithArguments("BarImpl.Moniker").WithLocation(4, 24),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_3()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_3");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_3");
var source3 = @"
public class BarImpl : IBar
{
public void SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(948674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/948674")]
[Fact]
public void UseSiteErrorViaImplementedInterfaceMember_4()
{
var source1 = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")]
[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")]
public struct ImageMoniker
{ }";
CSharpCompilation comp1 = CreateCompilationWithMscorlib45(source1, assemblyName: "Pia948674_4");
var source2 = @"
public interface IBar
{
void SetMoniker(ImageMoniker? moniker);
}";
CSharpCompilation comp2 = CreateCompilationWithMscorlib45(source2, new MetadataReference[] { new CSharpCompilationReference(comp1, embedInteropTypes: true) }, assemblyName: "Bar948674_4");
var source3 = @"
public class BarImpl : IBar
{
void IBar.SetMoniker(ImageMoniker? moniker)
{}
}";
CSharpCompilation comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { new CSharpCompilationReference(comp2), new CSharpCompilationReference(comp1, embedInteropTypes: true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
comp3 = CreateCompilationWithMscorlib45(source3, new MetadataReference[] { comp2.EmitToImageReference(), comp1.EmitToImageReference().WithEmbedInteropTypes(true) });
comp3.VerifyDiagnostics(
// (4,15): error CS0539: 'BarImpl.SetMoniker(ImageMoniker?)' in explicit interface declaration is not a member of interface
// void IBar.SetMoniker(ImageMoniker? moniker)
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "SetMoniker").WithArguments("BarImpl.SetMoniker(ImageMoniker?)").WithLocation(4, 15),
// (2,24): error CS1769: Type 'ImageMoniker?' from assembly 'Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
// public class BarImpl : IBar
Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "IBar").WithArguments("ImageMoniker?", "Bar948674_4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 24)
);
}
[WorkItem(541246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541246")]
[Fact]
public void NamespaceQualifiedGenericTypeName()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
}
class B
{
static int G = N.A<int>.F;
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void NamespaceQualifiedGenericTypeNameWrongArity()
{
var source =
@"namespace N
{
public class A<T>
{
public static T F;
}
public class B
{
public static int F;
}
public class B<T1, T2>
{
public static System.Tuple<T1, T2> F;
}
}
class C
{
static int TooMany = N.A<int, int>.F;
static int TooFew = N.A.F;
static int TooIndecisive = N.B<int>;
}";
CreateCompilation(source).VerifyDiagnostics(
// (19,28): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A<int, int>").WithArguments("N.A<T>", "type", "1"),
// (20,27): error CS0305: Using the generic type 'N.A<T>' requires '1' type arguments
//
Diagnostic(ErrorCode.ERR_BadArity, "A").WithArguments("N.A<T>", "type", "1"),
// (21,34): error CS0308: The non-generic type 'N.B' cannot be used with type arguments
//
Diagnostic(ErrorCode.ERR_HasNoTypeVars, "B<int>").WithArguments("N.B", "type")
);
}
[WorkItem(541570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541570")]
[Fact]
public void EnumNotMemberInConstructor()
{
var source =
@"enum E { A }
class C
{
public C(E e = E.A) { }
public E E { get { return E.A; } }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(541638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541638")]
[Fact]
public void KeywordAsLabelIdentifier()
{
var source =
@"class Program
{
static void Main(string[] args)
{
@int1:
System.Console.WriteLine();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,5): warning CS0164: This label has not been referenced
//
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "@int1"));
}
[WorkItem(541677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541677")]
[Fact]
public void AssignStaticEventToLocalVariable()
{
var source =
@"delegate void Foo();
class driver
{
public static event Foo e;
static void Main(string[] args)
{
Foo x = e;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
// Note: The locations for errors on generic methods are
// name only, while Dev11 uses name + type parameters.
[WorkItem(528743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528743")]
[Fact]
public void GenericMethodLocation()
{
var source =
@"interface I
{
void M1<T>() where T : class;
}
class C : I
{
public void M1<T>() { }
void M2<T>(this object o) { }
sealed void M3<T>() { }
internal static virtual void M4<T>() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,7): error CS1106: Extension method must be defined in a non-generic static class
// class C : I
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(5, 7),
// (7,17): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'I.M1<T>()'. Consider using an explicit interface implementation instead.
// public void M1<T>() { }
Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "I.M1<T>()").WithLocation(7, 17),
// (9,17): error CS0238: 'C.M3<T>()' cannot be sealed because it is not an override
// sealed void M3<T>() { }
Diagnostic(ErrorCode.ERR_SealedNonOverride, "M3").WithArguments("C.M3<T>()").WithLocation(9, 17),
// (10,34): error CS0112: A static member cannot be marked as 'virtual'
// internal static virtual void M4<T>() { }
Diagnostic(ErrorCode.ERR_StaticNotVirtual, "M4").WithArguments("virtual").WithLocation(10, 34)
);
}
[WorkItem(542391, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542391")]
[Fact]
public void PartialMethodOptionalParameters()
{
var source =
@"partial class C
{
partial void M1(object o);
partial void M1(object o = null) { }
partial void M2(object o = null);
partial void M2(object o) { }
partial void M3(object o = null);
partial void M3(object o = null) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M1(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o"),
// (8,28): warning CS1066: The default value specified for parameter 'o' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments
// partial void M3(object o = null) { }
Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "o").WithArguments("o")
);
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition1()
{
var source = @"
partial class C
{
partial void F(int i);
}
partial class C
{
partial void F(int j) { }
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
[Fact]
[WorkItem(598043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598043")]
public void PartialMethodParameterNamesFromDefinition2()
{
var source = @"
partial class C
{
partial void F(int j) { }
}
partial class C
{
partial void F(int i);
}
";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<MethodSymbol>("F");
Assert.Equal("i", method.Parameters[0].Name);
});
}
/// <summary>
/// Handle a mix of parameter errors for default values,
/// partial methods, and static parameter type.
/// </summary>
[Fact]
public void ParameterErrorsDefaultPartialMethodStaticType()
{
var source =
@"static class S { }
partial class C
{
partial void M(S s = new A());
partial void M(S s = new B()) { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(4, 18),
// (5,18): error CS0721: 'S': static types cannot be used as parameters
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M").WithArguments("S").WithLocation(5, 18),
// (5,30): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new B()) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(5, 30),
// (4,30): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// partial void M(S s = new A());
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(4, 30)
);
}
[WorkItem(543349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543349")]
[Fact]
public void Fixed()
{
var source =
@"class C
{
unsafe static void M(int[] arg)
{
fixed (int* ptr = arg) { }
fixed (int* ptr = arg) *ptr = 0;
fixed (int* ptr = arg) object o = null;
}
}";
CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(
// (7,32): error CS1023: Embedded statement cannot be a declaration or labeled statement
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "object o = null;").WithLocation(7, 32),
// (7,39): warning CS0219: The variable 'o' is assigned but its value is never used
// fixed (int* ptr = arg) object o = null;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "o").WithArguments("o").WithLocation(7, 39)
);
}
[WorkItem(1040171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040171")]
[Fact]
public void Bug1040171()
{
const string sourceCode = @"
class Program
{
static void Main(string[] args)
{
bool c = true;
foreach (string s in args)
label: c = false;
}
}
";
var compilation = CreateCompilation(sourceCode);
compilation.VerifyDiagnostics(
// (9,13): error CS1023: Embedded statement cannot be a declaration or labeled statement
// label: c = false;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "label: c = false;").WithLocation(9, 13),
// (9,13): warning CS0164: This label has not been referenced
// label: c = false;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(9, 13),
// (6,14): warning CS0219: The variable 'c' is assigned but its value is never used
// bool c = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(6, 14));
}
[Fact, WorkItem(543426, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543426")]
private void NestedInterfaceImplementationWithOuterGenericType()
{
CompileAndVerify(@"
namespace System.ServiceModel
{
class Pipeline<T>
{
interface IStage
{
void Process(T context);
}
class AsyncStage : IStage
{
void IStage.Process(T context) { }
}
}
}");
}
/// <summary>
/// Error types should be allowed as constant types.
/// </summary>
[Fact]
public void ErrorTypeConst()
{
var source =
@"class C
{
const C1 F1 = 0;
const C2 F2 = null;
static void M()
{
const C3 c3 = 0;
const C4 c4 = null;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,11): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1").WithLocation(3, 11),
// (4,11): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C2").WithArguments("C2").WithLocation(4, 11),
// (7,15): error CS0246: The type or namespace name 'C3' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C3").WithArguments("C3").WithLocation(7, 15),
// (8,15): error CS0246: The type or namespace name 'C4' could not be found (are you missing a using directive or an assembly reference?)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C4").WithArguments("C4").WithLocation(8, 15));
}
[WorkItem(543777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543777")]
[Fact]
public void DefaultParameterAtEndOfFile()
{
var source =
@"class C
{
static void M(object o = null,";
CreateCompilation(source).VerifyDiagnostics(
// (3,35): error CS1031: Type expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_TypeExpected, ""),
// Cascading:
// (3,35): error CS1001: Identifier expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (3,35): error CS1026: ) expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (3,35): error CS1002: ; expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_SemicolonExpected, ""),
// (3,35): error CS1513: } expected
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_RbraceExpected, ""),
// (3,35): error CS1737: Optional parameters must appear after all required parameters
// static void M(object o = null,
Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ""),
// (3,17): error CS0501: 'C.M(object, ?)' must declare a body because it is not
// marked abstract, extern, or partial static void M(object o = null,
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("C.M(object, ?)"));
}
[WorkItem(543814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543814")]
[Fact]
public void DuplicateNamedArgumentNullLiteral()
{
var source =
@"class C
{
static void M()
{
M("""",
arg: 0,
arg: null);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,9): error CS1501: No overload for method 'M' takes 3 arguments
// M("",
Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "3").WithLocation(5, 9));
}
[WorkItem(543820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543820")]
[Fact]
public void GenericAttributeClassWithMultipleParts()
{
var source =
@"class C<T> { }
class C<T> : System.Attribute { }";
CreateCompilation(source).VerifyDiagnostics(
// (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C'
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>"),
// (2,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class
// class C<T> : System.Attribute { }
Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute")
);
}
[WorkItem(543822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543822")]
[Fact]
public void InterfaceWithPartialMethodExplicitImplementation()
{
var source =
@"interface I
{
partial void I.M();
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics(
// (3,20): error CS0754: A partial method may not explicitly implement an interface method
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodNotExplicit, "M").WithLocation(3, 20),
// (3,20): error CS0751: A partial method must be declared within a partial type
// partial void I.M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 20),
// (3,20): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater.
// partial void I.M();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "M").WithArguments("default interface implementation", "8.0").WithLocation(3, 20),
// (3,18): error CS0540: 'I.M()': containing type does not implement interface 'I'
// partial void I.M();
Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("I.M()", "I").WithLocation(3, 18)
);
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructConstructor()
{
var source =
@"struct S
{
private readonly object x;
private readonly object y;
S(object x, object y)
{
try
{
this.x = x;
}
finally
{
this.y = y;
}
}
S(S o) : this(o.x, o.y) {}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(543827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543827")]
[Fact]
public void StructVersusTryFinally()
{
var source =
@"struct S
{
private object x;
private object y;
static void M()
{
S s1;
try { s1.x = null; } finally { s1.y = null; }
S s2 = s1;
s1.x = s1.y; s1.y = s1.x;
}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(544513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544513")]
[Fact()]
public void AnonTypesPropSameNameDiffType()
{
var source =
@"public class Test
{
public static void Main()
{
var p1 = new { Price = 495.00 };
var p2 = new { Price = ""36.50"" };
p1 = p2;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (8,14): error CS0029: Cannot implicitly convert type 'AnonymousType#1' to 'AnonymousType#2'
// p1 = p2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "p2").WithArguments("<anonymous type: string Price>", "<anonymous type: double Price>"));
}
[WorkItem(545869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545869")]
[Fact]
public void TestSealedOverriddenMembers()
{
CompileAndVerify(
@"using System;
internal abstract class Base
{
public virtual int Property
{
get { return 0; }
protected set { }
}
protected virtual event EventHandler Event
{
add { } remove { }
}
protected abstract void Method();
}
internal sealed class Derived : Base
{
public override int Property
{
get { return 1; }
protected set { }
}
protected override event EventHandler Event;
protected override void Method() { }
void UseEvent() { Event(null, null); }
}
internal sealed class Derived2 : Base
{
public override int Property
{
get; protected set;
}
protected override event EventHandler Event
{
add { } remove { }
}
protected override void Method() { }
}
class Program
{
static void Main() { }
}").VerifyDiagnostics();
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_01()
{
var source =
@"
class Program
{
[System.Diagnostics.DebuggerDisplay(this)]
static void Main(string[] args)
{
}
}";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact, WorkItem(1068547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068547")]
public void Bug1068547_02()
{
var source =
@"
[System.Diagnostics.DebuggerDisplay(this)]
";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.ThisExpression)).Cast<ThisExpressionSyntax>().Single();
var symbolInfo = model.GetSymbolInfo(node);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.NotReferencable, symbolInfo.CandidateReason);
}
[Fact]
public void RefReturningDelegateCreation()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateCreationBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void Test()
{
new D(M)();
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (15,15): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// new D(M)();
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(15, 15)
);
}
[Fact]
public void RefReturningDelegateArgument()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
ref int M()
{
return ref field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefReturningDelegateArgumentBad()
{
var text = @"
delegate ref int D();
class C
{
int field = 0;
int M()
{
return field;
}
void M(D d)
{
}
void Test()
{
M(M);
}
}
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (19,11): error CS8189: Ref mismatch between 'C.M()' and delegate 'D'
// M(M);
Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "M").WithArguments("C.M()", "D").WithLocation(19, 11)
);
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958()
{
const string source = @"
class C
{
static void Foo<T>()
{
T();
}
static void T() { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (6,9): error CS0119: 'T' is a type, which is not valid in the given context
// T();
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 9));
}
[Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")]
public void Bug1078958_2()
{
const string source = @"
class C
{
static void Foo<T>()
{
T<T>();
}
static void T() { }
static void T<U>() { }
}";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961()
{
const string source = @"
class C
{
const int T = 42;
static void Foo<T>(int x = T)
{
System.Console.Write(x);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "42");
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_2()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<T>([A(T)] int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var x = foo.Parameters[0];
var a = x.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_3()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
[A(T)]
static void Foo<T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var a = foo.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_4()
{
const string source = @"
class A : System.Attribute
{
public A(int i) { }
}
class C
{
const int T = 42;
static void Foo<[A(T)] T>(int x)
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var c = comp.GlobalNamespace.GetTypeMembers("C").Single();
var t = (FieldSymbol)c.GetMembers("T").Single();
var foo = (MethodSymbol)c.GetMembers("Foo").Single();
var tt = foo.TypeParameters[0];
var a = tt.GetAttributes()[0];
var i = a.ConstructorArguments.Single();
Assert.Equal((int)i.Value, (int)t.ConstantValue);
}
[Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")]
public void Bug1078961_5()
{
const string source = @"
class C
{
class T { }
static void Foo<T>(T x = default(T))
{
System.Console.Write((object)x == null);
}
static void Main()
{
Foo<object>();
}
}";
CompileAndVerify(source, expectedOutput: "True");
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_01()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
RunAction(A.B<string>.M0);
RunAction((Action)A.B<string>.M1);
}
private static void RunAction(Action action) { }
private class B<T>
{
public static void M0() { }
public static void M1() { }
}
}
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("A.B<string>.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("A.B<string>.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_02()
{
var sourceText = @"
class A
{
public delegate void MyDelegate<T>(T a);
public void Test()
{
UseMyDelegate((MyDelegate<int>)MyMethod);
UseMyDelegate((MyDelegate<long>)MyMethod);
UseMyDelegate((MyDelegate<float>)MyMethod);
UseMyDelegate((MyDelegate<double>)MyMethod);
}
private void UseMyDelegate<T>(MyDelegate<T> f) { }
private static void MyMethod(int a) { }
private static void MyMethod(long a) { }
private static void MyMethod(float a) { }
private static void MyMethod(double a) { }
}";
var compilation = CreateCompilation(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifiers = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(x => x.Identifier.ValueText.Equals("MyMethod")).ToArray();
Assert.Equal(4, identifiers.Length);
Assert.Equal("(MyDelegate<int>)MyMethod", identifiers[0].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int32 a)", model.GetSymbolInfo(identifiers[0]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<long>)MyMethod", identifiers[1].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Int64 a)", model.GetSymbolInfo(identifiers[1]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<float>)MyMethod", identifiers[2].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Single a)", model.GetSymbolInfo(identifiers[2]).Symbol.ToTestDisplayString());
Assert.Equal("(MyDelegate<double>)MyMethod", identifiers[3].Parent.ToString());
Assert.Equal("void A.MyMethod(System.Double a)", model.GetSymbolInfo(identifiers[3]).Symbol.ToTestDisplayString());
}
[Fact, WorkItem(3096, "https://github.com/dotnet/roslyn/issues/3096")]
public void CastToDelegate_03()
{
var sourceText = @"namespace NS
{
public static class A
{
public delegate void Action();
public static void M()
{
var b = new A.B<string>();
RunAction(b.M0);
RunAction((Action)b.M1);
}
private static void RunAction(Action action) { }
public class B<T>
{
}
public static void M0<T>(this B<T> x) { }
public static void M1<T>(this B<T> x) { }
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceText, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var identifierNameM0 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M0"));
Assert.Equal("b.M0", identifierNameM0.Parent.ToString());
var m0Symbol = model.GetSymbolInfo(identifierNameM0);
Assert.Equal("void NS.A.B<System.String>.M0<System.String>()", m0Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m0Symbol.CandidateReason);
var identifierNameM1 = tree
.GetRoot()
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(x => x.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression) && x.Identifier.ValueText.Equals("M1"));
Assert.Equal("b.M1", identifierNameM1.Parent.ToString());
var m1Symbol = model.GetSymbolInfo(identifierNameM1);
Assert.Equal("void NS.A.B<System.String>.M1<System.String>()", m1Symbol.Symbol.ToTestDisplayString());
Assert.Equal(CandidateReason.None, m1Symbol.CandidateReason);
}
[Fact, WorkItem(5170, "https://github.com/dotnet/roslyn/issues/5170")]
public void TypeOfBinderParameter()
{
var sourceText = @"
using System.Linq;
using System.Text;
public static class LazyToStringExtension
{
public static string LazyToString<T>(this T obj) where T : class
{
StringBuilder sb = new StringBuilder();
typeof(T)
.GetProperties(System.Reflection.BindingFlags.Public)
.Select(x => x.GetValue(obj))
}
}";
var compilation = CreateCompilationWithMscorlib40(sourceText, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics(
// (12,42): error CS1002: ; expected
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(12, 42),
// (12,28): error CS1501: No overload for method 'GetValue' takes 1 arguments
// .Select(x => x.GetValue(obj))
Diagnostic(ErrorCode.ERR_BadArgCount, "GetValue").WithArguments("GetValue", "1").WithLocation(12, 28),
// (7,26): error CS0161: 'LazyToStringExtension.LazyToString<T>(T)': not all code paths return a value
// public static string LazyToString<T>(this T obj) where T : class
Diagnostic(ErrorCode.ERR_ReturnExpected, "LazyToString").WithArguments("LazyToStringExtension.LazyToString<T>(T)").WithLocation(7, 26));
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = node.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
Assert.Equal("System.Reflection.PropertyInfo x", model.GetDeclaredSymbol(param).ToTestDisplayString());
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void DelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
var x = new Action<int>(i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,40): error CS1001: Identifier expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 40),
// (7,40): error CS1026: ) expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 40),
// (7,40): error CS1002: ; expected
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 40),
// (7,38): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// var x = new Action<int>(i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(7520, "https://github.com/dotnet/roslyn/issues/7520")]
public void ImplicitDelegateCreationWithIncompleteLambda()
{
var source =
@"
using System;
class C
{
public void F()
{
Action<int> x = i => i.
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,32): error CS1001: Identifier expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(7, 32),
// (7,32): error CS1002: ; expected
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 32),
// (7,30): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action<int> x = i => i.
Diagnostic(ErrorCode.ERR_IllegalStatement, @"i.
").WithLocation(7, 30)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single();
var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single();
var symbol1 = model.GetDeclaredSymbol(param);
Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString());
var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName));
var symbol2 = model.GetSymbolInfo(id).Symbol;
Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString());
Assert.Same(symbol1, symbol2);
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_01()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_02()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(38, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(1, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_03()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
IApplicationBuilder Use(Func<HttpContext, Func<Task>, Task> middleware);
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(31, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(5128, "https://github.com/dotnet/roslyn/issues/5128")]
public void GetMemberGroupInsideIncompleteLambda_04()
{
var source =
@"
using System;
using System.Threading.Tasks;
public delegate Task RequestDelegate(HttpContext context);
public class AuthenticationResult { }
public abstract class AuthenticationManager
{
public abstract Task<AuthenticationResult> AuthenticateAsync(string authenticationScheme);
}
public abstract class HttpContext
{
public abstract AuthenticationManager Authentication { get; }
}
interface IApplicationBuilder
{
}
static class IApplicationBuilderExtensions
{
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<RequestDelegate, RequestDelegate> middleware)
{
return app;
}
public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware)
{
return app;
}
}
class C
{
void M(IApplicationBuilder app)
{
app.Use(async (ctx, next) =>
{
await ctx.Authentication.AuthenticateAsync();
});
}
}
";
var comp = CreateCompilationWithMscorlib40(source, new[] { TestMetadata.Net40.SystemCore });
comp.VerifyDiagnostics(
// (41,38): error CS7036: There is no argument given that corresponds to the required formal parameter 'authenticationScheme' of 'AuthenticationManager.AuthenticateAsync(string)'
// await ctx.Authentication.AuthenticateAsync();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AuthenticateAsync").WithArguments("authenticationScheme", "AuthenticationManager.AuthenticateAsync(string)").WithLocation(42, 38)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "Use").Single().Parent;
Assert.Equal("app.Use", node1.ToString());
var group1 = model.GetMemberGroup(node1);
Assert.Equal(2, group1.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", group1[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)",
group1[1].ToTestDisplayString());
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.Equal(2, symbolInfo1.CandidateSymbols.Length);
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<RequestDelegate, RequestDelegate> middleware)", symbolInfo1.CandidateSymbols[0].ToTestDisplayString());
Assert.Equal("IApplicationBuilder IApplicationBuilder.Use(System.Func<HttpContext, System.Func<System.Threading.Tasks.Task>, System.Threading.Tasks.Task> middleware)", symbolInfo1.CandidateSymbols[1].ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason);
var node = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "AuthenticateAsync").Single().Parent;
Assert.Equal("ctx.Authentication.AuthenticateAsync", node.ToString());
var group = model.GetMemberGroup(node);
Assert.Equal("System.Threading.Tasks.Task<AuthenticationResult> AuthenticationManager.AuthenticateAsync(System.String authenticationScheme)", group.Single().ToTestDisplayString());
}
[Fact, WorkItem(7101, "https://github.com/dotnet/roslyn/issues/7101")]
public void UsingStatic_01()
{
var source =
@"
using System;
using static ClassWithNonStaticMethod;
using static Extension1;
class Program
{
static void Main(string[] args)
{
var instance = new Program();
instance.NonStaticMethod();
}
private void NonStaticMethod()
{
MathMin(0, 1);
MathMax(0, 1);
MathMax2(0, 1);
int x;
x = F1;
x = F2;
x.MathMax2(3);
}
}
class ClassWithNonStaticMethod
{
public static int MathMax(int a, int b)
{
return Math.Max(a, b);
}
public int MathMin(int a, int b)
{
return Math.Min(a, b);
}
public int F2 = 0;
}
static class Extension1
{
public static int MathMax2(this int a, int b)
{
return Math.Max(a, b);
}
public static int F1 = 0;
}
static class Extension2
{
public static int MathMax3(this int a, int b)
{
return Math.Max(a, b);
}
}
";
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics(
// (16,9): error CS0103: The name 'MathMin' does not exist in the current context
// MathMin(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMin").WithArguments("MathMin").WithLocation(16, 9),
// (18,9): error CS0103: The name 'MathMax2' does not exist in the current context
// MathMax2(0, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "MathMax2").WithArguments("MathMax2").WithLocation(18, 9),
// (22,13): error CS0103: The name 'F2' does not exist in the current context
// x = F2;
Diagnostic(ErrorCode.ERR_NameNotInContext, "F2").WithArguments("F2").WithLocation(22, 13)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "MathMin").Single().Parent;
Assert.Equal("MathMin(0, 1)", node1.ToString());
var names = model.LookupNames(node1.SpanStart);
Assert.False(names.Contains("MathMin"));
Assert.True(names.Contains("MathMax"));
Assert.True(names.Contains("F1"));
Assert.False(names.Contains("F2"));
Assert.False(names.Contains("MathMax2"));
Assert.False(names.Contains("MathMax3"));
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMin").IsEmpty);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "MathMax").Length);
Assert.Equal(1, model.LookupSymbols(node1.SpanStart, name: "F1").Length);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "F2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax2").IsEmpty);
Assert.True(model.LookupSymbols(node1.SpanStart, name: "MathMax3").IsEmpty);
var symbols = model.LookupSymbols(node1.SpanStart);
Assert.False(symbols.Where(s => s.Name == "MathMin").Any());
Assert.True(symbols.Where(s => s.Name == "MathMax").Any());
Assert.True(symbols.Where(s => s.Name == "F1").Any());
Assert.False(symbols.Where(s => s.Name == "F2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax2").Any());
Assert.False(symbols.Where(s => s.Name == "MathMax3").Any());
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraint()
{
var code = @"
using static Test<System.String>;
public static class Test<T> where T : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static Test<System.String>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static Test<System.String>;").WithLocation(2, 1),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>'
// using static Test<System.String>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test<System.String>").WithArguments("Test<T>", "T", "string").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticGenericConstraintNestedType()
{
var code = @"
using static A<A<int>[]>.B;
class A<T> where T : class
{
internal static class B { }
}
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<A<int>[]>.B;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T>'
// using static A<A<int>[]>.B;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<A<int>[]>.B").WithArguments("A<T>", "T", "int").WithLocation(2, 14));
}
[Fact, WorkItem(30726, "https://github.com/dotnet/roslyn/issues/30726")]
public void UsingStaticMultipleGenericConstraints()
{
var code = @"
using static A<int, string>;
static class A<T, U> where T : class where U : struct { }
";
CreateCompilationWithMscorlib45(code).VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using static A<int, string>;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static A<int, string>;").WithLocation(2, 1),
// (2,14): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "T", "int").WithLocation(2, 14),
// (2,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<T, U>'
// using static A<int, string>;
Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "A<int, string>").WithArguments("A<T, U>", "U", "string").WithLocation(2, 14));
}
[Fact, WorkItem(8234, "https://github.com/dotnet/roslyn/issues/8234")]
public void EventAccessInTypeNameContext()
{
var source =
@"
class Program
{
static void Main() {}
event System.EventHandler E1;
void Test(Program x)
{
System.Console.WriteLine();
x.E1.E
System.Console.WriteLine();
}
void Dummy()
{
E1 = null;
var x = E1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,15): error CS1001: Identifier expected
// x.E1.E
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(11, 15),
// (11,15): error CS1002: ; expected
// x.E1.E
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15),
// (11,9): error CS0118: 'x' is a variable but is used like a type
// x.E1.E
Diagnostic(ErrorCode.ERR_BadSKknown, "x").WithArguments("x", "variable", "type").WithLocation(11, 9)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)n).Identifier.ValueText == "E").Single().Parent;
Assert.Equal("x.E1.E", node1.ToString());
Assert.Equal(SyntaxKind.QualifiedName, node1.Kind());
var node2 = ((QualifiedNameSyntax)node1).Left;
Assert.Equal("x.E1", node2.ToString());
var symbolInfo2 = model.GetSymbolInfo(node2);
Assert.Null(symbolInfo2.Symbol);
Assert.Equal("event System.EventHandler Program.E1", symbolInfo2.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo2.CandidateReason);
var symbolInfo1 = model.GetSymbolInfo(node1);
Assert.Null(symbolInfo1.Symbol);
Assert.True(symbolInfo1.CandidateSymbols.IsEmpty);
}
[Fact, WorkItem(13617, "https://github.com/dotnet/roslyn/issues/13617")]
public void MissingTypeArgumentInGenericExtensionMethod()
{
var source =
@"
public static class FooExtensions
{
public static object ExtensionMethod0(this object obj) => default(object);
public static T ExtensionMethod1<T>(this object obj) => default(T);
public static T1 ExtensionMethod2<T1, T2>(this object obj) => default(T1);
}
public class Class1
{
public void Test()
{
var omittedArg0 = ""string literal"".ExtensionMethod0<>();
var omittedArg1 = ""string literal"".ExtensionMethod1<>();
var omittedArg2 = ""string literal"".ExtensionMethod2<>();
var omittedArgFunc0 = ""string literal"".ExtensionMethod0<>;
var omittedArgFunc1 = ""string literal"".ExtensionMethod1<>;
var omittedArgFunc2 = ""string literal"".ExtensionMethod2<>;
var moreArgs0 = ""string literal"".ExtensionMethod0<int>();
var moreArgs1 = ""string literal"".ExtensionMethod1<int, bool>();
var moreArgs2 = ""string literal"".ExtensionMethod2<int, bool, string>();
var lessArgs1 = ""string literal"".ExtensionMethod1();
var lessArgs2 = ""string literal"".ExtensionMethod2<int>();
var nonExistingMethod0 = ""string literal"".ExtensionMethodNotFound0();
var nonExistingMethod1 = ""string literal"".ExtensionMethodNotFound1<int>();
var nonExistingMethod2 = ""string literal"".ExtensionMethodNotFound2<int, string>();
System.Func<object> delegateConversion0 = ""string literal"".ExtensionMethod0<>;
System.Func<object> delegateConversion1 = ""string literal"".ExtensionMethod1<>;
System.Func<object> delegateConversion2 = ""string literal"".ExtensionMethod2<>;
var exactArgs0 = ""string literal"".ExtensionMethod0();
var exactArgs1 = ""string literal"".ExtensionMethod1<int>();
var exactArgs2 = ""string literal"".ExtensionMethod2<int, bool>();
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (13,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(13, 27),
// (13,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg0 = "string literal".ExtensionMethod0<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(13, 44),
// (14,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg1 = "string literal".ExtensionMethod1<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(14, 27),
// (15,27): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(15, 27),
// (15,44): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArg2 = "string literal".ExtensionMethod2<>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(15, 44),
// (17,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(17, 31),
// (17,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(17, 48),
// (18,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(18, 31),
// (18,13): error CS0815: Cannot assign method group to an implicitly-typed variable
// var omittedArgFunc1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, @"omittedArgFunc1 = ""string literal"".ExtensionMethod1<>").WithArguments("method group").WithLocation(18, 13),
// (19,31): error CS8389: Omitting the type argument is not allowed in the current context
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(19, 31),
// (19,48): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var omittedArgFunc2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(19, 48),
// (21,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs0 = "string literal".ExtensionMethod0<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<int>").WithArguments("string", "ExtensionMethod0").WithLocation(21, 42),
// (22,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod1' and no accessible extension method 'ExtensionMethod1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs1 = "string literal".ExtensionMethod1<int, bool>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod1<int, bool>").WithArguments("string", "ExtensionMethod1").WithLocation(22, 42),
// (23,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var moreArgs2 = "string literal".ExtensionMethod2<int, bool, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int, bool, string>").WithArguments("string", "ExtensionMethod2").WithLocation(23, 42),
// (25,42): error CS0411: The type arguments for method 'FooExtensions.ExtensionMethod1<T>(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// var lessArgs1 = "string literal".ExtensionMethod1();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "ExtensionMethod1").WithArguments("FooExtensions.ExtensionMethod1<T>(object)").WithLocation(25, 42),
// (26,42): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var lessArgs2 = "string literal".ExtensionMethod2<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<int>").WithArguments("string", "ExtensionMethod2").WithLocation(26, 42),
// (28,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound0' and no accessible extension method 'ExtensionMethodNotFound0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod0 = "string literal".ExtensionMethodNotFound0();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound0").WithArguments("string", "ExtensionMethodNotFound0").WithLocation(28, 51),
// (29,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound1' and no accessible extension method 'ExtensionMethodNotFound1' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod1 = "string literal".ExtensionMethodNotFound1<int>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound1<int>").WithArguments("string", "ExtensionMethodNotFound1").WithLocation(29, 51),
// (30,51): error CS1061: 'string' does not contain a definition for 'ExtensionMethodNotFound2' and no accessible extension method 'ExtensionMethodNotFound2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// var nonExistingMethod2 = "string literal".ExtensionMethodNotFound2<int, string>();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethodNotFound2<int, string>").WithArguments("string", "ExtensionMethodNotFound2").WithLocation(30, 51),
// (32,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod0<>").WithLocation(32, 51),
// (32,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod0' and no accessible extension method 'ExtensionMethod0' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion0 = "string literal".ExtensionMethod0<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod0<>").WithArguments("string", "ExtensionMethod0").WithLocation(32, 68),
// (33,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod1<>").WithLocation(33, 51),
// (33,51): error CS0407: '? FooExtensions.ExtensionMethod1<?>(object)' has the wrong return type
// System.Func<object> delegateConversion1 = "string literal".ExtensionMethod1<>;
Diagnostic(ErrorCode.ERR_BadRetType, @"""string literal"".ExtensionMethod1<>").WithArguments("FooExtensions.ExtensionMethod1<?>(object)", "?").WithLocation(33, 51),
// (34,51): error CS8389: Omitting the type argument is not allowed in the current context
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_OmittedTypeArgument, @"""string literal"".ExtensionMethod2<>").WithLocation(34, 51),
// (34,68): error CS1061: 'string' does not contain a definition for 'ExtensionMethod2' and no accessible extension method 'ExtensionMethod2' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// System.Func<object> delegateConversion2 = "string literal".ExtensionMethod2<>;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ExtensionMethod2<>").WithArguments("string", "ExtensionMethod2").WithLocation(34, 68));
}
[WorkItem(22757, "https://github.com/dotnet/roslyn/issues/22757")]
[Fact]
public void MethodGroupConversionNoReceiver()
{
var source =
@"using System;
using System.Collections.Generic;
class A
{
class B
{
void F()
{
IEnumerable<string> c = null;
c.S(G);
}
}
object G(string s)
{
return null;
}
}
static class E
{
internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f)
{
throw new NotImplementedException();
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source);
comp.VerifyDiagnostics(
// (10,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)'
// c.S(G);
Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(10, 17));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "G").First();
var info = model.GetSymbolInfo(node);
Assert.Equal("System.Object A.G(System.String s)", info.Symbol.ToTestDisplayString());
}
[Fact]
public void BindingLambdaArguments_DuplicateNamedArguments()
{
var compilation = CreateCompilation(@"
using System;
class X
{
void M<T>(T arg1, Func<T, T> arg2)
{
}
void N()
{
M(arg1: 5, arg2: x => x, arg2: y => y);
}
}").VerifyDiagnostics(
// (10,34): error CS1740: Named argument 'arg2' cannot be specified multiple times
// M(arg1: 5, arg2: x => 0, arg2: y => 0);
Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "arg2").WithArguments("arg2").WithLocation(10, 34));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true);
var lambda = tree.GetRoot().DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(s => s.Parameter.Identifier.Text == "x");
var typeInfo = model.GetTypeInfo(lambda.Body);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Extensibility/Completion/ExportCompletionProviderAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Completion;
namespace Microsoft.CodeAnalysis.Editor
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportCompletionProviderMef1Attribute : ExportAttribute
{
public string Name { get; }
public string Language { get; }
public ExportCompletionProviderMef1Attribute(string name, string language)
: base(typeof(CompletionProvider))
{
this.Name = name ?? throw new ArgumentNullException(nameof(name));
this.Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Completion;
namespace Microsoft.CodeAnalysis.Editor
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportCompletionProviderMef1Attribute : ExportAttribute
{
public string Name { get; }
public string Language { get; }
public ExportCompletionProviderMef1Attribute(string name, string language)
: base(typeof(CompletionProvider))
{
this.Name = name ?? throw new ArgumentNullException(nameof(name));
this.Language = language ?? throw new ArgumentNullException(nameof(language));
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Operations/OperationNodes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Operations
{
/// <summary>
/// Use this to create IOperation when we don't have proper specific IOperation yet for given language construct
/// </summary>
internal sealed class NoneOperation : Operation
{
public NoneOperation(ImmutableArray<IOperation> children, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) :
base(semanticModel, syntax, isImplicit)
{
Children = SetParentOperation(children, this);
Type = type;
OperationConstantValue = constantValue;
}
internal ImmutableArray<IOperation> Children { get; }
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when index < Children.Length
=> Children[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index))
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (!Children.IsEmpty) return (true, 0, 0);
else goto case 0;
case 0 when previousIndex + 1 < Children.Length:
return (true, 0, previousIndex + 1);
case 0:
case 1:
return (false, 1, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override ITypeSymbol? Type { get; }
internal override ConstantValue? OperationConstantValue { get; }
public override OperationKind Kind => OperationKind.None;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitNoneOperation(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitNoneOperation(this, argument);
}
}
internal partial class ConversionOperation
{
public IMethodSymbol? OperatorMethod => Conversion.MethodSymbol;
}
internal sealed partial class InvalidOperation : Operation, IInvalidOperation
{
public InvalidOperation(ImmutableArray<IOperation> children, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) :
base(semanticModel, syntax, isImplicit)
{
// we don't allow null children.
Debug.Assert(children.All(o => o != null));
Children = SetParentOperation(children, this);
Type = type;
OperationConstantValue = constantValue;
}
internal ImmutableArray<IOperation> Children { get; }
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when index < Children.Length
=> Children[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index))
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (!Children.IsEmpty) return (true, 0, 0);
else goto case 0;
case 0 when previousIndex + 1 < Children.Length:
return (true, 0, previousIndex + 1);
case 0:
case 1:
return (false, 1, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override ITypeSymbol? Type { get; }
internal override ConstantValue? OperationConstantValue { get; }
public override OperationKind Kind => OperationKind.Invalid;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitInvalid(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitInvalid(this, argument);
}
}
internal sealed class FlowAnonymousFunctionOperation : Operation, IFlowAnonymousFunctionOperation
{
public readonly ControlFlowGraphBuilder.Context Context;
public readonly IAnonymousFunctionOperation Original;
public FlowAnonymousFunctionOperation(in ControlFlowGraphBuilder.Context context, IAnonymousFunctionOperation original, bool isImplicit) :
base(semanticModel: null, original.Syntax, isImplicit)
{
Context = context;
Original = original;
}
public IMethodSymbol Symbol => Original.Symbol;
protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index));
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue);
public override OperationKind Kind => OperationKind.FlowAnonymousFunction;
public override ITypeSymbol? Type => null;
internal override ConstantValue? OperationConstantValue => null;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitFlowAnonymousFunction(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitFlowAnonymousFunction(this, argument);
}
}
internal abstract partial class BaseMemberReferenceOperation : IMemberReferenceOperation
{
public abstract ISymbol Member { get; }
}
internal sealed partial class MethodReferenceOperation
{
public override ISymbol Member => Method;
}
internal sealed partial class PropertyReferenceOperation
{
public override ISymbol Member => Property;
}
internal sealed partial class EventReferenceOperation
{
public override ISymbol Member => Event;
}
internal sealed partial class FieldReferenceOperation
{
public override ISymbol Member => Field;
}
internal sealed partial class RangeCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Range;
}
internal sealed partial class SingleValueCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.SingleValue;
}
internal sealed partial class RelationalCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Relational;
}
internal sealed partial class DefaultCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Default;
}
internal sealed partial class PatternCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Pattern;
}
internal abstract partial class HasDynamicArgumentsExpression : Operation
{
protected HasDynamicArgumentsExpression(ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(semanticModel, syntax, isImplicit)
{
Arguments = SetParentOperation(arguments, this);
ArgumentNames = argumentNames;
ArgumentRefKinds = argumentRefKinds;
Type = type;
}
public ImmutableArray<string> ArgumentNames { get; }
public ImmutableArray<RefKind> ArgumentRefKinds { get; }
public ImmutableArray<IOperation> Arguments { get; }
public override ITypeSymbol? Type { get; }
}
internal sealed partial class DynamicObjectCreationOperation : HasDynamicArgumentsExpression, IDynamicObjectCreationOperation
{
public DynamicObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit)
{
Initializer = SetParentOperation(initializer, this);
}
public IObjectOrCollectionInitializerOperation? Initializer { get; }
internal override ConstantValue? OperationConstantValue => null;
public override OperationKind Kind => OperationKind.DynamicObjectCreation;
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when index < Arguments.Length
=> Arguments[index],
1 when Initializer != null
=> Initializer,
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (!Arguments.IsEmpty) return (true, 0, 0);
else goto case 0;
case 0 when previousIndex + 1 < Arguments.Length:
return (true, 0, previousIndex + 1);
case 0:
if (Initializer != null) return (true, 1, 0);
else goto case 1;
case 1:
case 2:
return (false, 2, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override void Accept(OperationVisitor visitor)
{
visitor.VisitDynamicObjectCreation(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitDynamicObjectCreation(this, argument);
}
}
internal sealed partial class DynamicInvocationOperation : HasDynamicArgumentsExpression, IDynamicInvocationOperation
{
public DynamicInvocationOperation(IOperation operation, ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit)
{
Operation = SetParentOperation(operation, this);
}
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when Operation != null
=> Operation,
1 when index < Arguments.Length
=> Arguments[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (Operation != null) return (true, 0, 0);
else goto case 0;
case 0:
if (!Arguments.IsEmpty) return (true, 1, 0);
else goto case 1;
case 1 when previousIndex + 1 < Arguments.Length:
return (true, 1, previousIndex + 1);
case 1:
case 2:
return (false, 2, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public IOperation Operation { get; }
internal override ConstantValue? OperationConstantValue => null;
public override OperationKind Kind => OperationKind.DynamicInvocation;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitDynamicInvocation(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitDynamicInvocation(this, argument);
}
}
internal sealed partial class DynamicIndexerAccessOperation : HasDynamicArgumentsExpression, IDynamicIndexerAccessOperation
{
public DynamicIndexerAccessOperation(IOperation operation, ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit)
{
Operation = SetParentOperation(operation, this);
}
public IOperation Operation { get; }
internal override ConstantValue? OperationConstantValue => null;
public override OperationKind Kind => OperationKind.DynamicIndexerAccess;
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when Operation != null
=> Operation,
1 when index < Arguments.Length
=> Arguments[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (Operation != null) return (true, 0, 0);
else goto case 0;
case 0:
if (!Arguments.IsEmpty) return (true, 1, 0);
else goto case 1;
case 1 when previousIndex + 1 < Arguments.Length:
return (true, 1, previousIndex + 1);
case 1:
case 2:
return (false, 2, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override void Accept(OperationVisitor visitor)
{
visitor.VisitDynamicIndexerAccess(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitDynamicIndexerAccess(this, argument);
}
}
internal sealed partial class ForEachLoopOperation
{
public override LoopKind LoopKind => LoopKind.ForEach;
}
internal sealed partial class ForLoopOperation
{
public override LoopKind LoopKind => LoopKind.For;
}
internal sealed partial class ForToLoopOperation
{
public override LoopKind LoopKind => LoopKind.ForTo;
}
internal sealed partial class WhileLoopOperation
{
protected override IOperation GetCurrent(int slot, int index)
{
return ConditionIsTop ? getCurrentSwitchTop() : getCurrentSwitchBottom();
IOperation getCurrentSwitchTop()
=> slot switch
{
0 when Condition != null
=> Condition,
1 when Body != null
=> Body,
2 when IgnoredCondition != null
=> IgnoredCondition,
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
IOperation getCurrentSwitchBottom()
=> slot switch
{
0 when Body != null
=> Body,
1 when Condition != null
=> Condition,
2 when IgnoredCondition != null
=> IgnoredCondition,
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
}
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
return ConditionIsTop ? moveNextConditionIsTop() : moveNextConditionIsBottom();
(bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsTop()
{
switch (previousSlot)
{
case -1:
if (Condition != null) return (true, 0, 0);
else goto case 0;
case 0:
if (Body != null) return (true, 1, 0);
else goto case 1;
case 1:
if (IgnoredCondition != null) return (true, 2, 0);
else goto case 2;
case 2:
case 3:
return (false, 3, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
(bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsBottom()
{
switch (previousSlot)
{
case -1:
if (Body != null) return (true, 0, 0);
else goto case 0;
case 0:
if (Condition != null) return (true, 1, 0);
else goto case 1;
case 1:
if (IgnoredCondition != null) return (true, 2, 0);
else goto case 2;
case 2:
case 3:
return (false, 3, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
}
public override LoopKind LoopKind => LoopKind.While;
}
internal sealed partial class FlowCaptureReferenceOperation
{
public FlowCaptureReferenceOperation(int id, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue) :
this(new CaptureId(id), semanticModel: null, syntax: syntax, type: type, constantValue: constantValue, isImplicit: true)
{
}
}
internal sealed partial class FlowCaptureOperation
{
public FlowCaptureOperation(int id, SyntaxNode syntax, IOperation value) :
this(new CaptureId(id), value, semanticModel: null, syntax: syntax, isImplicit: true)
{
Debug.Assert(value != null);
}
}
internal sealed partial class IsNullOperation
{
public IsNullOperation(SyntaxNode syntax, IOperation operand, ITypeSymbol type, ConstantValue? constantValue) :
this(operand, semanticModel: null, syntax: syntax, type: type, constantValue: constantValue, isImplicit: true)
{
Debug.Assert(operand != null);
}
}
internal sealed partial class CaughtExceptionOperation
{
public CaughtExceptionOperation(SyntaxNode syntax, ITypeSymbol type) :
this(semanticModel: null, syntax: syntax, type: type, isImplicit: true)
{
}
}
internal sealed partial class StaticLocalInitializationSemaphoreOperation
{
public StaticLocalInitializationSemaphoreOperation(ILocalSymbol local, SyntaxNode syntax, ITypeSymbol type) :
this(local, semanticModel: null, syntax, type, isImplicit: true)
{
}
}
internal sealed partial class BlockOperation
{
/// <summary>
/// This creates a block that can be used for temporary, internal applications that require a block composed of
/// statements from another block. Blocks created by this API violate IOperation tree constraints and should
/// never be exposed from a public API.
/// </summary>
public static BlockOperation CreateTemporaryBlock(ImmutableArray<IOperation> statements, SemanticModel semanticModel, SyntaxNode syntax)
=> new BlockOperation(statements, semanticModel, syntax);
private BlockOperation(ImmutableArray<IOperation> statements, SemanticModel semanticModel, SyntaxNode syntax)
: base(semanticModel, syntax, isImplicit: true)
{
// Intentionally skipping SetParentOperation: this is used by CreateTemporaryBlock for the purposes of the
// control flow factory, to temporarily create a new block for use in emulating the "block" a using variable
// declaration introduces. These statements already have a parent node, and `SetParentOperation`'s verification
// would fail because that parent isn't this. In error cases, the parent can also be a switch statement if
// the using declaration was used directly as an embedded statement in the case without a block.
Debug.Assert(statements.All(s => s.Parent != this && s.Parent!.Kind is OperationKind.Block or OperationKind.SwitchCase));
Operations = statements;
Locals = ImmutableArray<ILocalSymbol>.Empty;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Operations
{
/// <summary>
/// Use this to create IOperation when we don't have proper specific IOperation yet for given language construct
/// </summary>
internal sealed class NoneOperation : Operation
{
public NoneOperation(ImmutableArray<IOperation> children, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) :
base(semanticModel, syntax, isImplicit)
{
Children = SetParentOperation(children, this);
Type = type;
OperationConstantValue = constantValue;
}
internal ImmutableArray<IOperation> Children { get; }
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when index < Children.Length
=> Children[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index))
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (!Children.IsEmpty) return (true, 0, 0);
else goto case 0;
case 0 when previousIndex + 1 < Children.Length:
return (true, 0, previousIndex + 1);
case 0:
case 1:
return (false, 1, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override ITypeSymbol? Type { get; }
internal override ConstantValue? OperationConstantValue { get; }
public override OperationKind Kind => OperationKind.None;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitNoneOperation(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitNoneOperation(this, argument);
}
}
internal partial class ConversionOperation
{
public IMethodSymbol? OperatorMethod => Conversion.MethodSymbol;
}
internal sealed partial class InvalidOperation : Operation, IInvalidOperation
{
public InvalidOperation(ImmutableArray<IOperation> children, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue, bool isImplicit) :
base(semanticModel, syntax, isImplicit)
{
// we don't allow null children.
Debug.Assert(children.All(o => o != null));
Children = SetParentOperation(children, this);
Type = type;
OperationConstantValue = constantValue;
}
internal ImmutableArray<IOperation> Children { get; }
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when index < Children.Length
=> Children[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index))
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (!Children.IsEmpty) return (true, 0, 0);
else goto case 0;
case 0 when previousIndex + 1 < Children.Length:
return (true, 0, previousIndex + 1);
case 0:
case 1:
return (false, 1, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override ITypeSymbol? Type { get; }
internal override ConstantValue? OperationConstantValue { get; }
public override OperationKind Kind => OperationKind.Invalid;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitInvalid(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitInvalid(this, argument);
}
}
internal sealed class FlowAnonymousFunctionOperation : Operation, IFlowAnonymousFunctionOperation
{
public readonly ControlFlowGraphBuilder.Context Context;
public readonly IAnonymousFunctionOperation Original;
public FlowAnonymousFunctionOperation(in ControlFlowGraphBuilder.Context context, IAnonymousFunctionOperation original, bool isImplicit) :
base(semanticModel: null, original.Syntax, isImplicit)
{
Context = context;
Original = original;
}
public IMethodSymbol Symbol => Original.Symbol;
protected override IOperation GetCurrent(int slot, int index) => throw ExceptionUtilities.UnexpectedValue((slot, index));
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex) => (false, int.MinValue, int.MinValue);
public override OperationKind Kind => OperationKind.FlowAnonymousFunction;
public override ITypeSymbol? Type => null;
internal override ConstantValue? OperationConstantValue => null;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitFlowAnonymousFunction(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitFlowAnonymousFunction(this, argument);
}
}
internal abstract partial class BaseMemberReferenceOperation : IMemberReferenceOperation
{
public abstract ISymbol Member { get; }
}
internal sealed partial class MethodReferenceOperation
{
public override ISymbol Member => Method;
}
internal sealed partial class PropertyReferenceOperation
{
public override ISymbol Member => Property;
}
internal sealed partial class EventReferenceOperation
{
public override ISymbol Member => Event;
}
internal sealed partial class FieldReferenceOperation
{
public override ISymbol Member => Field;
}
internal sealed partial class RangeCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Range;
}
internal sealed partial class SingleValueCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.SingleValue;
}
internal sealed partial class RelationalCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Relational;
}
internal sealed partial class DefaultCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Default;
}
internal sealed partial class PatternCaseClauseOperation
{
public override CaseKind CaseKind => CaseKind.Pattern;
}
internal abstract partial class HasDynamicArgumentsExpression : Operation
{
protected HasDynamicArgumentsExpression(ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(semanticModel, syntax, isImplicit)
{
Arguments = SetParentOperation(arguments, this);
ArgumentNames = argumentNames;
ArgumentRefKinds = argumentRefKinds;
Type = type;
}
public ImmutableArray<string> ArgumentNames { get; }
public ImmutableArray<RefKind> ArgumentRefKinds { get; }
public ImmutableArray<IOperation> Arguments { get; }
public override ITypeSymbol? Type { get; }
}
internal sealed partial class DynamicObjectCreationOperation : HasDynamicArgumentsExpression, IDynamicObjectCreationOperation
{
public DynamicObjectCreationOperation(IObjectOrCollectionInitializerOperation? initializer, ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit)
{
Initializer = SetParentOperation(initializer, this);
}
public IObjectOrCollectionInitializerOperation? Initializer { get; }
internal override ConstantValue? OperationConstantValue => null;
public override OperationKind Kind => OperationKind.DynamicObjectCreation;
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when index < Arguments.Length
=> Arguments[index],
1 when Initializer != null
=> Initializer,
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (!Arguments.IsEmpty) return (true, 0, 0);
else goto case 0;
case 0 when previousIndex + 1 < Arguments.Length:
return (true, 0, previousIndex + 1);
case 0:
if (Initializer != null) return (true, 1, 0);
else goto case 1;
case 1:
case 2:
return (false, 2, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override void Accept(OperationVisitor visitor)
{
visitor.VisitDynamicObjectCreation(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitDynamicObjectCreation(this, argument);
}
}
internal sealed partial class DynamicInvocationOperation : HasDynamicArgumentsExpression, IDynamicInvocationOperation
{
public DynamicInvocationOperation(IOperation operation, ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit)
{
Operation = SetParentOperation(operation, this);
}
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when Operation != null
=> Operation,
1 when index < Arguments.Length
=> Arguments[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (Operation != null) return (true, 0, 0);
else goto case 0;
case 0:
if (!Arguments.IsEmpty) return (true, 1, 0);
else goto case 1;
case 1 when previousIndex + 1 < Arguments.Length:
return (true, 1, previousIndex + 1);
case 1:
case 2:
return (false, 2, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public IOperation Operation { get; }
internal override ConstantValue? OperationConstantValue => null;
public override OperationKind Kind => OperationKind.DynamicInvocation;
public override void Accept(OperationVisitor visitor)
{
visitor.VisitDynamicInvocation(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitDynamicInvocation(this, argument);
}
}
internal sealed partial class DynamicIndexerAccessOperation : HasDynamicArgumentsExpression, IDynamicIndexerAccessOperation
{
public DynamicIndexerAccessOperation(IOperation operation, ImmutableArray<IOperation> arguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> argumentRefKinds, SemanticModel? semanticModel, SyntaxNode syntax, ITypeSymbol? type, bool isImplicit) :
base(arguments, argumentNames, argumentRefKinds, semanticModel, syntax, type, isImplicit)
{
Operation = SetParentOperation(operation, this);
}
public IOperation Operation { get; }
internal override ConstantValue? OperationConstantValue => null;
public override OperationKind Kind => OperationKind.DynamicIndexerAccess;
protected override IOperation GetCurrent(int slot, int index)
=> slot switch
{
0 when Operation != null
=> Operation,
1 when index < Arguments.Length
=> Arguments[index],
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
switch (previousSlot)
{
case -1:
if (Operation != null) return (true, 0, 0);
else goto case 0;
case 0:
if (!Arguments.IsEmpty) return (true, 1, 0);
else goto case 1;
case 1 when previousIndex + 1 < Arguments.Length:
return (true, 1, previousIndex + 1);
case 1:
case 2:
return (false, 2, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
public override void Accept(OperationVisitor visitor)
{
visitor.VisitDynamicIndexerAccess(this);
}
public override TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument) where TResult : default
{
return visitor.VisitDynamicIndexerAccess(this, argument);
}
}
internal sealed partial class ForEachLoopOperation
{
public override LoopKind LoopKind => LoopKind.ForEach;
}
internal sealed partial class ForLoopOperation
{
public override LoopKind LoopKind => LoopKind.For;
}
internal sealed partial class ForToLoopOperation
{
public override LoopKind LoopKind => LoopKind.ForTo;
}
internal sealed partial class WhileLoopOperation
{
protected override IOperation GetCurrent(int slot, int index)
{
return ConditionIsTop ? getCurrentSwitchTop() : getCurrentSwitchBottom();
IOperation getCurrentSwitchTop()
=> slot switch
{
0 when Condition != null
=> Condition,
1 when Body != null
=> Body,
2 when IgnoredCondition != null
=> IgnoredCondition,
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
IOperation getCurrentSwitchBottom()
=> slot switch
{
0 when Body != null
=> Body,
1 when Condition != null
=> Condition,
2 when IgnoredCondition != null
=> IgnoredCondition,
_ => throw ExceptionUtilities.UnexpectedValue((slot, index)),
};
}
protected override (bool hasNext, int nextSlot, int nextIndex) MoveNext(int previousSlot, int previousIndex)
{
return ConditionIsTop ? moveNextConditionIsTop() : moveNextConditionIsBottom();
(bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsTop()
{
switch (previousSlot)
{
case -1:
if (Condition != null) return (true, 0, 0);
else goto case 0;
case 0:
if (Body != null) return (true, 1, 0);
else goto case 1;
case 1:
if (IgnoredCondition != null) return (true, 2, 0);
else goto case 2;
case 2:
case 3:
return (false, 3, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
(bool hasNext, int nextSlot, int nextIndex) moveNextConditionIsBottom()
{
switch (previousSlot)
{
case -1:
if (Body != null) return (true, 0, 0);
else goto case 0;
case 0:
if (Condition != null) return (true, 1, 0);
else goto case 1;
case 1:
if (IgnoredCondition != null) return (true, 2, 0);
else goto case 2;
case 2:
case 3:
return (false, 3, 0);
default:
throw ExceptionUtilities.UnexpectedValue((previousSlot, previousIndex));
}
}
}
public override LoopKind LoopKind => LoopKind.While;
}
internal sealed partial class FlowCaptureReferenceOperation
{
public FlowCaptureReferenceOperation(int id, SyntaxNode syntax, ITypeSymbol? type, ConstantValue? constantValue) :
this(new CaptureId(id), semanticModel: null, syntax: syntax, type: type, constantValue: constantValue, isImplicit: true)
{
}
}
internal sealed partial class FlowCaptureOperation
{
public FlowCaptureOperation(int id, SyntaxNode syntax, IOperation value) :
this(new CaptureId(id), value, semanticModel: null, syntax: syntax, isImplicit: true)
{
Debug.Assert(value != null);
}
}
internal sealed partial class IsNullOperation
{
public IsNullOperation(SyntaxNode syntax, IOperation operand, ITypeSymbol type, ConstantValue? constantValue) :
this(operand, semanticModel: null, syntax: syntax, type: type, constantValue: constantValue, isImplicit: true)
{
Debug.Assert(operand != null);
}
}
internal sealed partial class CaughtExceptionOperation
{
public CaughtExceptionOperation(SyntaxNode syntax, ITypeSymbol type) :
this(semanticModel: null, syntax: syntax, type: type, isImplicit: true)
{
}
}
internal sealed partial class StaticLocalInitializationSemaphoreOperation
{
public StaticLocalInitializationSemaphoreOperation(ILocalSymbol local, SyntaxNode syntax, ITypeSymbol type) :
this(local, semanticModel: null, syntax, type, isImplicit: true)
{
}
}
internal sealed partial class BlockOperation
{
/// <summary>
/// This creates a block that can be used for temporary, internal applications that require a block composed of
/// statements from another block. Blocks created by this API violate IOperation tree constraints and should
/// never be exposed from a public API.
/// </summary>
public static BlockOperation CreateTemporaryBlock(ImmutableArray<IOperation> statements, SemanticModel semanticModel, SyntaxNode syntax)
=> new BlockOperation(statements, semanticModel, syntax);
private BlockOperation(ImmutableArray<IOperation> statements, SemanticModel semanticModel, SyntaxNode syntax)
: base(semanticModel, syntax, isImplicit: true)
{
// Intentionally skipping SetParentOperation: this is used by CreateTemporaryBlock for the purposes of the
// control flow factory, to temporarily create a new block for use in emulating the "block" a using variable
// declaration introduces. These statements already have a parent node, and `SetParentOperation`'s verification
// would fail because that parent isn't this. In error cases, the parent can also be a switch statement if
// the using declaration was used directly as an embedded statement in the case without a block.
Debug.Assert(statements.All(s => s.Parent != this && s.Parent!.Kind is OperationKind.Block or OperationKind.SwitchCase));
Operations = statements;
Locals = ImmutableArray<ILocalSymbol>.Empty;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core.Wpf/LineSeparators/LineSeparatorTaggerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.LineSeparators
{
/// <summary>
/// This factory is called to create taggers that provide information about where line
/// separators go.
/// </summary>
[Export(typeof(ITaggerProvider))]
[TagType(typeof(LineSeparatorTag))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
internal partial class LineSeparatorTaggerProvider : AsynchronousTaggerProvider<LineSeparatorTag>
{
private readonly IEditorFormatMap _editorFormatMap;
protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.LineSeparator);
private readonly object _lineSeperatorTagGate = new object();
private LineSeparatorTag _lineSeparatorTag;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LineSeparatorTaggerProvider(
IThreadingContext threadingContext,
IEditorFormatMapService editorFormatMapService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, listenerProvider.GetListener(FeatureAttribute.LineSeparators))
{
_editorFormatMap = editorFormatMapService.GetEditorFormatMap("text");
_editorFormatMap.FormatMappingChanged += OnFormatMappingChanged;
_lineSeparatorTag = new LineSeparatorTag(_editorFormatMap);
}
protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate;
private void OnFormatMappingChanged(object sender, FormatItemsEventArgs e)
{
lock (_lineSeperatorTagGate)
{
_lineSeparatorTag = new LineSeparatorTag(_editorFormatMap);
}
}
protected override ITaggerEventSource CreateEventSource(
ITextView textView, ITextBuffer subjectBuffer)
{
return TaggerEventSources.Compose(
new EditorFormatMapChangedEventSource(_editorFormatMap),
TaggerEventSources.OnTextChanged(subjectBuffer));
}
protected override async Task ProduceTagsAsync(TaggerContext<LineSeparatorTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition)
{
var cancellationToken = context.CancellationToken;
var document = documentSnapshotSpan.Document;
if (document == null)
{
return;
}
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
if (!documentOptions.GetOption(FeatureOnOffOptions.LineSeparator))
{
return;
}
LineSeparatorTag tag;
lock (_lineSeperatorTagGate)
{
tag = _lineSeparatorTag;
}
using (Logger.LogBlock(FunctionId.Tagger_LineSeparator_TagProducer_ProduceTags, cancellationToken))
{
var snapshotSpan = documentSnapshotSpan.SnapshotSpan;
var lineSeparatorService = document.GetLanguageService<ILineSeparatorService>();
var lineSeparatorSpans = await lineSeparatorService.GetLineSeparatorsAsync(document, snapshotSpan.Span.ToTextSpan(), cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
foreach (var span in lineSeparatorSpans)
{
context.AddTag(new TagSpan<LineSeparatorTag>(span.ToSnapshotSpan(snapshotSpan.Snapshot), tag));
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.LineSeparators
{
/// <summary>
/// This factory is called to create taggers that provide information about where line
/// separators go.
/// </summary>
[Export(typeof(ITaggerProvider))]
[TagType(typeof(LineSeparatorTag))]
[ContentType(ContentTypeNames.CSharpContentType)]
[ContentType(ContentTypeNames.VisualBasicContentType)]
internal partial class LineSeparatorTaggerProvider : AsynchronousTaggerProvider<LineSeparatorTag>
{
private readonly IEditorFormatMap _editorFormatMap;
protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.LineSeparator);
private readonly object _lineSeperatorTagGate = new object();
private LineSeparatorTag _lineSeparatorTag;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LineSeparatorTaggerProvider(
IThreadingContext threadingContext,
IEditorFormatMapService editorFormatMapService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, listenerProvider.GetListener(FeatureAttribute.LineSeparators))
{
_editorFormatMap = editorFormatMapService.GetEditorFormatMap("text");
_editorFormatMap.FormatMappingChanged += OnFormatMappingChanged;
_lineSeparatorTag = new LineSeparatorTag(_editorFormatMap);
}
protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate;
private void OnFormatMappingChanged(object sender, FormatItemsEventArgs e)
{
lock (_lineSeperatorTagGate)
{
_lineSeparatorTag = new LineSeparatorTag(_editorFormatMap);
}
}
protected override ITaggerEventSource CreateEventSource(
ITextView textView, ITextBuffer subjectBuffer)
{
return TaggerEventSources.Compose(
new EditorFormatMapChangedEventSource(_editorFormatMap),
TaggerEventSources.OnTextChanged(subjectBuffer));
}
protected override async Task ProduceTagsAsync(TaggerContext<LineSeparatorTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition)
{
var cancellationToken = context.CancellationToken;
var document = documentSnapshotSpan.Document;
if (document == null)
{
return;
}
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
if (!documentOptions.GetOption(FeatureOnOffOptions.LineSeparator))
{
return;
}
LineSeparatorTag tag;
lock (_lineSeperatorTagGate)
{
tag = _lineSeparatorTag;
}
using (Logger.LogBlock(FunctionId.Tagger_LineSeparator_TagProducer_ProduceTags, cancellationToken))
{
var snapshotSpan = documentSnapshotSpan.SnapshotSpan;
var lineSeparatorService = document.GetLanguageService<ILineSeparatorService>();
var lineSeparatorSpans = await lineSeparatorService.GetLineSeparatorsAsync(document, snapshotSpan.Span.ToTextSpan(), cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
foreach (var span in lineSeparatorSpans)
{
context.AddTag(new TagSpan<LineSeparatorTag>(span.ToSnapshotSpan(snapshotSpan.Snapshot), tag));
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Classification/SyntaxClassification/SyntacticChangeRangeComputer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
/// <summary>
/// Computes a syntactic text change range that determines the range of a document that was changed by an edit. The
/// portions outside this change range are guaranteed to be syntactically identical (see <see
/// cref="SyntaxNode.IsIncrementallyIdenticalTo"/>). This algorithm is intended to be <em>fast</em>. It is
/// technically linear in the number of nodes and tokens that may need to examined. However, in practice, it should
/// operate in sub-linear time as it will bail the moment tokens don't match, and it's able to skip over matching
/// nodes fully without examining the contents of those nodes. This is intended for consumers that want a
/// reasonably accurate change range computer, but do not want to spend an inordinate amount of time getting the
/// most accurate and minimal result possible.
/// </summary>
/// <remarks>
/// This computation is not guaranteed to be minimal. It may return a range that includes parts that are unchanged.
/// This means it is also legal for the change range to just specify the entire file was changed. The quality of
/// results will depend on how well the parsers did with incremental parsing, and how much time is given to do the
/// comparison. In practice, for large files (i.e. 15kloc) with standard types of edits, this generally returns
/// results in around 50-100 usecs on a i7 3GHz desktop.
/// <para>
/// This algorithm will respect the timeout provided to the best of abilities. If any information has been computed
/// when the timeout elapses, it will be returned.
/// </para>
/// </remarks>
internal static class SyntacticChangeRangeComputer
{
private static readonly ObjectPool<Stack<SyntaxNodeOrToken>> s_pool = new(() => new());
public static TextChangeRange ComputeSyntacticChangeRange(SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken)
{
if (oldRoot == newRoot)
return default;
var stopwatch = SharedStopwatch.StartNew();
// We will be comparing the trees for two documents like so:
//
// --------------------------------------------
// old: | |
// --------------------------------------------
//
// ---------------------------------------------------
// new: | |
// ---------------------------------------------------
//
// (Note that `new` could be smaller or the same length as `old`, it makes no difference).
//
// The algorithm will sweep in from both sides, as long as the nodes and tokens it's touching on each side
// are 'identical' (i.e. are the exact same green node, and were thus reused over an incremental parse.).
// This will leave us with:
//
// --------------------------------------------
// old: | CLW | | CRW |
// --------------------------------------------
// | | \ \
// ---------------------------------------------------
// new: | CLW | | CRW |
// ---------------------------------------------------
//
// Where CLW and CRW refer to the common-left-width and common-right-width respectively. The part in between
// this s the change range:
//
// --------------------------------------------
// old: | |**********************| |
// --------------------------------------------
// |**************************\
// ---------------------------------------------------
// new: | |*****************************| |
// ---------------------------------------------------
//
// The Span changed will go from `[CLW, Old_Width - CRW)`, and the NewLength will be `New_Width - CLW - CRW`
var commonLeftWidth = ComputeCommonLeftWidth();
if (commonLeftWidth == null)
{
// The trees were effectively identical (even if the children were different). Return that there was no
// text change.
return default;
}
// Only compute the right side if we have time for it. Otherwise, assume there is nothing in common there.
var commonRightWidth = 0;
if (stopwatch.Elapsed < timeout)
commonRightWidth = ComputeCommonRightWidth();
var oldRootWidth = oldRoot.FullWidth();
var newRootWidth = newRoot.FullWidth();
Contract.ThrowIfTrue(commonLeftWidth > oldRootWidth);
Contract.ThrowIfTrue(commonLeftWidth > newRootWidth);
Contract.ThrowIfTrue(commonRightWidth > oldRootWidth);
Contract.ThrowIfTrue(commonRightWidth > newRootWidth);
// it's possible for the common left/right to overlap. This can happen as some tokens
// in the parser have a true shared underlying state, so they may get consumed both on
// a leftward and rightward walk. Cap the right width so that it never overlaps hte left
// width in either the old or new tree.
commonRightWidth = Math.Min(commonRightWidth, oldRootWidth - commonLeftWidth.Value);
commonRightWidth = Math.Min(commonRightWidth, newRootWidth - commonLeftWidth.Value);
return new TextChangeRange(
TextSpan.FromBounds(start: commonLeftWidth.Value, end: oldRootWidth - commonRightWidth),
newRootWidth - commonLeftWidth.Value - commonRightWidth);
int? ComputeCommonLeftWidth()
{
using var leftOldStack = s_pool.GetPooledObject();
using var leftNewStack = s_pool.GetPooledObject();
var oldStack = leftOldStack.Object;
var newStack = leftNewStack.Object;
oldStack.Push(oldRoot);
newStack.Push(newRoot);
while (oldStack.Count > 0 && newStack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var currentOld = oldStack.Pop();
var currentNew = newStack.Pop();
Contract.ThrowIfFalse(currentOld.FullSpan.Start == currentNew.FullSpan.Start);
// If the two nodes/tokens were the same just skip past them. They're part of the common left width.
if (currentOld.IsIncrementallyIdenticalTo(currentNew))
continue;
// if we reached a token for either of these, then we can't break things down any further, and we hit
// the furthest point they are common.
if (currentOld.IsToken || currentNew.IsToken)
return currentOld.FullSpan.Start;
// Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as
// we could be. But the caller wants the results asap.
if (stopwatch.Elapsed > timeout)
return currentOld.FullSpan.Start;
// we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the
// class, the class node would be new, but there might be many member nodes that were the same that we'd
// want to see and skip. Crumble the node and deal with its left side.
//
// Reverse so that we process the leftmost child first and walk left to right.
foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens().Reverse())
oldStack.Push(nodeOrToken);
foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens().Reverse())
newStack.Push(nodeOrToken);
}
// If we consumed all of 'new', then the length of the new doc is what we have in common.
if (oldStack.Count > 0)
return newRoot.FullSpan.Length;
// If we consumed all of 'old', then the length of the old doc is what we have in common.
if (newStack.Count > 0)
return oldRoot.FullSpan.Length;
// We consumed both stacks entirely. That means the trees were identical (though the root was different). Return null to signify no change to the doc.
return null;
}
int ComputeCommonRightWidth()
{
using var rightOldStack = s_pool.GetPooledObject();
using var rightNewStack = s_pool.GetPooledObject();
var oldStack = rightOldStack.Object;
var newStack = rightNewStack.Object;
oldStack.Push(oldRoot);
newStack.Push(newRoot);
while (oldStack.Count > 0 && newStack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var currentOld = oldStack.Pop();
var currentNew = newStack.Pop();
// The width on the right we've moved past on both old/new should be the same.
Contract.ThrowIfFalse((oldRoot.FullSpan.End - currentOld.FullSpan.End) ==
(newRoot.FullSpan.End - currentNew.FullSpan.End));
// If the two nodes/tokens were the same just skip past them. They're part of the common right width.
// Critically though, we can only skip past if this wasn't already something we consumed when determining
// the common left width. If this was common the left side, we can't consider it common to the right,
// otherwise we could end up with overlapping regions of commonality.
//
// This can occur in incremental settings when the similar tokens are written successsively.
// Because the parser can reuse underlying token data, it may end up with many incrementally
// identical tokens in a row.
if (currentOld.IsIncrementallyIdenticalTo(currentNew) &&
currentOld.FullSpan.Start >= commonLeftWidth &&
currentNew.FullSpan.Start >= commonLeftWidth)
{
continue;
}
// if we reached a token for either of these, then we can't break things down any further, and we hit
// the furthest point they are common.
if (currentOld.IsToken || currentNew.IsToken)
return oldRoot.FullSpan.End - currentOld.FullSpan.End;
// Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as
// we could be. But the caller wants the results asap.
if (stopwatch.Elapsed > timeout)
return oldRoot.FullSpan.End - currentOld.FullSpan.End;
// we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the
// class, the class node would be new, but there might be many member nodes following the edited node
// that were the same that we'd want to see and skip. Crumble the node and deal with its right side.
//
// Do not reverse the children. We want to process the rightmost child first and walk right to left.
foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens())
oldStack.Push(nodeOrToken);
foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens())
newStack.Push(nodeOrToken);
}
// If we consumed all of 'new', then the length of the new doc is what we have in common.
if (oldStack.Count > 0)
return newRoot.FullSpan.Length;
// If we consumed all of 'old', then the length of the old doc is what we have in common.
if (newStack.Count > 0)
return oldRoot.FullSpan.Length;
// We consumed both stacks entirely. That means the trees were identical (though the root was
// different). We should never get here. If we were the same, then walking from the left should have
// consumed everything and already bailed out.
throw ExceptionUtilities.Unreachable;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
/// <summary>
/// Computes a syntactic text change range that determines the range of a document that was changed by an edit. The
/// portions outside this change range are guaranteed to be syntactically identical (see <see
/// cref="SyntaxNode.IsIncrementallyIdenticalTo"/>). This algorithm is intended to be <em>fast</em>. It is
/// technically linear in the number of nodes and tokens that may need to examined. However, in practice, it should
/// operate in sub-linear time as it will bail the moment tokens don't match, and it's able to skip over matching
/// nodes fully without examining the contents of those nodes. This is intended for consumers that want a
/// reasonably accurate change range computer, but do not want to spend an inordinate amount of time getting the
/// most accurate and minimal result possible.
/// </summary>
/// <remarks>
/// This computation is not guaranteed to be minimal. It may return a range that includes parts that are unchanged.
/// This means it is also legal for the change range to just specify the entire file was changed. The quality of
/// results will depend on how well the parsers did with incremental parsing, and how much time is given to do the
/// comparison. In practice, for large files (i.e. 15kloc) with standard types of edits, this generally returns
/// results in around 50-100 usecs on a i7 3GHz desktop.
/// <para>
/// This algorithm will respect the timeout provided to the best of abilities. If any information has been computed
/// when the timeout elapses, it will be returned.
/// </para>
/// </remarks>
internal static class SyntacticChangeRangeComputer
{
private static readonly ObjectPool<Stack<SyntaxNodeOrToken>> s_pool = new(() => new());
public static TextChangeRange ComputeSyntacticChangeRange(SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken)
{
if (oldRoot == newRoot)
return default;
var stopwatch = SharedStopwatch.StartNew();
// We will be comparing the trees for two documents like so:
//
// --------------------------------------------
// old: | |
// --------------------------------------------
//
// ---------------------------------------------------
// new: | |
// ---------------------------------------------------
//
// (Note that `new` could be smaller or the same length as `old`, it makes no difference).
//
// The algorithm will sweep in from both sides, as long as the nodes and tokens it's touching on each side
// are 'identical' (i.e. are the exact same green node, and were thus reused over an incremental parse.).
// This will leave us with:
//
// --------------------------------------------
// old: | CLW | | CRW |
// --------------------------------------------
// | | \ \
// ---------------------------------------------------
// new: | CLW | | CRW |
// ---------------------------------------------------
//
// Where CLW and CRW refer to the common-left-width and common-right-width respectively. The part in between
// this s the change range:
//
// --------------------------------------------
// old: | |**********************| |
// --------------------------------------------
// |**************************\
// ---------------------------------------------------
// new: | |*****************************| |
// ---------------------------------------------------
//
// The Span changed will go from `[CLW, Old_Width - CRW)`, and the NewLength will be `New_Width - CLW - CRW`
var commonLeftWidth = ComputeCommonLeftWidth();
if (commonLeftWidth == null)
{
// The trees were effectively identical (even if the children were different). Return that there was no
// text change.
return default;
}
// Only compute the right side if we have time for it. Otherwise, assume there is nothing in common there.
var commonRightWidth = 0;
if (stopwatch.Elapsed < timeout)
commonRightWidth = ComputeCommonRightWidth();
var oldRootWidth = oldRoot.FullWidth();
var newRootWidth = newRoot.FullWidth();
Contract.ThrowIfTrue(commonLeftWidth > oldRootWidth);
Contract.ThrowIfTrue(commonLeftWidth > newRootWidth);
Contract.ThrowIfTrue(commonRightWidth > oldRootWidth);
Contract.ThrowIfTrue(commonRightWidth > newRootWidth);
// it's possible for the common left/right to overlap. This can happen as some tokens
// in the parser have a true shared underlying state, so they may get consumed both on
// a leftward and rightward walk. Cap the right width so that it never overlaps hte left
// width in either the old or new tree.
commonRightWidth = Math.Min(commonRightWidth, oldRootWidth - commonLeftWidth.Value);
commonRightWidth = Math.Min(commonRightWidth, newRootWidth - commonLeftWidth.Value);
return new TextChangeRange(
TextSpan.FromBounds(start: commonLeftWidth.Value, end: oldRootWidth - commonRightWidth),
newRootWidth - commonLeftWidth.Value - commonRightWidth);
int? ComputeCommonLeftWidth()
{
using var leftOldStack = s_pool.GetPooledObject();
using var leftNewStack = s_pool.GetPooledObject();
var oldStack = leftOldStack.Object;
var newStack = leftNewStack.Object;
oldStack.Push(oldRoot);
newStack.Push(newRoot);
while (oldStack.Count > 0 && newStack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var currentOld = oldStack.Pop();
var currentNew = newStack.Pop();
Contract.ThrowIfFalse(currentOld.FullSpan.Start == currentNew.FullSpan.Start);
// If the two nodes/tokens were the same just skip past them. They're part of the common left width.
if (currentOld.IsIncrementallyIdenticalTo(currentNew))
continue;
// if we reached a token for either of these, then we can't break things down any further, and we hit
// the furthest point they are common.
if (currentOld.IsToken || currentNew.IsToken)
return currentOld.FullSpan.Start;
// Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as
// we could be. But the caller wants the results asap.
if (stopwatch.Elapsed > timeout)
return currentOld.FullSpan.Start;
// we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the
// class, the class node would be new, but there might be many member nodes that were the same that we'd
// want to see and skip. Crumble the node and deal with its left side.
//
// Reverse so that we process the leftmost child first and walk left to right.
foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens().Reverse())
oldStack.Push(nodeOrToken);
foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens().Reverse())
newStack.Push(nodeOrToken);
}
// If we consumed all of 'new', then the length of the new doc is what we have in common.
if (oldStack.Count > 0)
return newRoot.FullSpan.Length;
// If we consumed all of 'old', then the length of the old doc is what we have in common.
if (newStack.Count > 0)
return oldRoot.FullSpan.Length;
// We consumed both stacks entirely. That means the trees were identical (though the root was different). Return null to signify no change to the doc.
return null;
}
int ComputeCommonRightWidth()
{
using var rightOldStack = s_pool.GetPooledObject();
using var rightNewStack = s_pool.GetPooledObject();
var oldStack = rightOldStack.Object;
var newStack = rightNewStack.Object;
oldStack.Push(oldRoot);
newStack.Push(newRoot);
while (oldStack.Count > 0 && newStack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var currentOld = oldStack.Pop();
var currentNew = newStack.Pop();
// The width on the right we've moved past on both old/new should be the same.
Contract.ThrowIfFalse((oldRoot.FullSpan.End - currentOld.FullSpan.End) ==
(newRoot.FullSpan.End - currentNew.FullSpan.End));
// If the two nodes/tokens were the same just skip past them. They're part of the common right width.
// Critically though, we can only skip past if this wasn't already something we consumed when determining
// the common left width. If this was common the left side, we can't consider it common to the right,
// otherwise we could end up with overlapping regions of commonality.
//
// This can occur in incremental settings when the similar tokens are written successsively.
// Because the parser can reuse underlying token data, it may end up with many incrementally
// identical tokens in a row.
if (currentOld.IsIncrementallyIdenticalTo(currentNew) &&
currentOld.FullSpan.Start >= commonLeftWidth &&
currentNew.FullSpan.Start >= commonLeftWidth)
{
continue;
}
// if we reached a token for either of these, then we can't break things down any further, and we hit
// the furthest point they are common.
if (currentOld.IsToken || currentNew.IsToken)
return oldRoot.FullSpan.End - currentOld.FullSpan.End;
// Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as
// we could be. But the caller wants the results asap.
if (stopwatch.Elapsed > timeout)
return oldRoot.FullSpan.End - currentOld.FullSpan.End;
// we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the
// class, the class node would be new, but there might be many member nodes following the edited node
// that were the same that we'd want to see and skip. Crumble the node and deal with its right side.
//
// Do not reverse the children. We want to process the rightmost child first and walk right to left.
foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens())
oldStack.Push(nodeOrToken);
foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens())
newStack.Push(nodeOrToken);
}
// If we consumed all of 'new', then the length of the new doc is what we have in common.
if (oldStack.Count > 0)
return newRoot.FullSpan.Length;
// If we consumed all of 'old', then the length of the old doc is what we have in common.
if (newStack.Count > 0)
return oldRoot.FullSpan.Length;
// We consumed both stacks entirely. That means the trees were identical (though the root was
// different). We should never get here. If we were the same, then walking from the left should have
// consumed everything and already bailed out.
throw ExceptionUtilities.Unreachable;
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Symbols/EventSymbolExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static class EventSymbolExtensions
{
internal static MethodSymbol GetOwnOrInheritedAccessor(this EventSymbol @event, bool isAdder)
{
return isAdder
? @event.GetOwnOrInheritedAddMethod()
: @event.GetOwnOrInheritedRemoveMethod();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static class EventSymbolExtensions
{
internal static MethodSymbol GetOwnOrInheritedAccessor(this EventSymbol @event, bool isAdder)
{
return isAdder
? @event.GetOwnOrInheritedAddMethod()
: @event.GetOwnOrInheritedRemoveMethod();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./eng/config/test/Core/InstallTraceListener.cs | // <auto-generated/>
using System.Runtime.CompilerServices;
using Roslyn.Test.Utilities;
internal sealed class InitializeTestModule
{
[ModuleInitializer]
internal static void Initializer()
{
RuntimeHelpers.RunModuleConstructor(typeof(TestBase).Module.ModuleHandle);
}
}
| // <auto-generated/>
using System.Runtime.CompilerServices;
using Roslyn.Test.Utilities;
internal sealed class InitializeTestModule
{
[ModuleInitializer]
internal static void Initializer()
{
RuntimeHelpers.RunModuleConstructor(typeof(TestBase).Module.ModuleHandle);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/ExpressionBodyPreference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
/// <remarks>
/// Note: the order of this enum is important. We originally only supported two values,
/// and we encoded this as a bool with 'true = WhenPossible' and 'false = never'. To
/// preserve compatibility we map the false value to 0 and the true value to 1. All new
/// values go after these.
/// </remarks>
internal enum ExpressionBodyPreference
{
// Value can not be changed. 'false' was the "never" value back when we used CodeStyleOption<bool>
// and that will map to '0' when derialized.
Never = 0,
// Value can not be changed. 'true' was the 'whenever possible' value back when we used
// CodeStyleOption<bool> and that will map to '1' when deserialized.
WhenPossible = 1,
WhenOnSingleLine = 2,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
/// <remarks>
/// Note: the order of this enum is important. We originally only supported two values,
/// and we encoded this as a bool with 'true = WhenPossible' and 'false = never'. To
/// preserve compatibility we map the false value to 0 and the true value to 1. All new
/// values go after these.
/// </remarks>
internal enum ExpressionBodyPreference
{
// Value can not be changed. 'false' was the "never" value back when we used CodeStyleOption<bool>
// and that will map to '0' when derialized.
Never = 0,
// Value can not be changed. 'true' was the 'whenever possible' value back when we used
// CodeStyleOption<bool> and that will map to '1' when deserialized.
WhenPossible = 1,
WhenOnSingleLine = 2,
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/EditorConfigSettings/Formatting/ViewModel/FormattingViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider;
using Microsoft.Internal.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.ViewModel
{
internal partial class FormattingViewModel : SettingsViewModelBase<
FormattingSetting,
FormattingViewModel.SettingsSnapshotFactory,
FormattingViewModel.SettingsEntriesSnapshot>
{
public FormattingViewModel(ISettingsProvider<FormattingSetting> data,
IWpfTableControlProvider controlProvider,
ITableManagerProvider tableMangerProvider)
: base(data, controlProvider, tableMangerProvider)
{ }
public override string Identifier => "Whitespace";
protected override SettingsSnapshotFactory CreateSnapshotFactory(ISettingsProvider<FormattingSetting> data)
=> new(data);
protected override IEnumerable<ColumnState2> GetInitialColumnStates()
=> new[]
{
new ColumnState2(ColumnDefinitions.Formatting.Category, isVisible: false, width: 0, groupingPriority: 1),
new ColumnState2(ColumnDefinitions.Formatting.Description, isVisible: true, width: 0),
new ColumnState2(ColumnDefinitions.Formatting.Value, isVisible: true, width: 0)
};
protected override string[] GetFixedColumns()
=> new[]
{
ColumnDefinitions.Formatting.Category,
ColumnDefinitions.Formatting.Description,
ColumnDefinitions.Formatting.Value
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider;
using Microsoft.Internal.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.ViewModel
{
internal partial class FormattingViewModel : SettingsViewModelBase<
FormattingSetting,
FormattingViewModel.SettingsSnapshotFactory,
FormattingViewModel.SettingsEntriesSnapshot>
{
public FormattingViewModel(ISettingsProvider<FormattingSetting> data,
IWpfTableControlProvider controlProvider,
ITableManagerProvider tableMangerProvider)
: base(data, controlProvider, tableMangerProvider)
{ }
public override string Identifier => "Whitespace";
protected override SettingsSnapshotFactory CreateSnapshotFactory(ISettingsProvider<FormattingSetting> data)
=> new(data);
protected override IEnumerable<ColumnState2> GetInitialColumnStates()
=> new[]
{
new ColumnState2(ColumnDefinitions.Formatting.Category, isVisible: false, width: 0, groupingPriority: 1),
new ColumnState2(ColumnDefinitions.Formatting.Description, isVisible: true, width: 0),
new ColumnState2(ColumnDefinitions.Formatting.Value, isVisible: true, width: 0)
};
protected override string[] GetFixedColumns()
=> new[]
{
ColumnDefinitions.Formatting.Category,
ColumnDefinitions.Formatting.Description,
ColumnDefinitions.Formatting.Value
};
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Preview/DifferenceViewerPreview.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
internal class DifferenceViewerPreview : IDisposable
{
private IDifferenceViewer _viewer;
public DifferenceViewerPreview(IDifferenceViewer viewer)
{
Contract.ThrowIfNull(viewer);
_viewer = viewer;
}
public IDifferenceViewer Viewer => _viewer;
public void Dispose()
{
GC.SuppressFinalize(this);
if (_viewer != null && !_viewer.IsClosed)
{
_viewer.Close();
}
_viewer = null;
}
~DifferenceViewerPreview()
{
// make sure we are not leaking diff viewer
// we can't close the view from finalizer thread since it must be same
// thread (owner thread) this UI is created.
if (Environment.HasShutdownStarted)
{
return;
}
FatalError.ReportAndCatch(new Exception($"Dispose is not called how? viewer state : {_viewer.IsClosed}"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview
{
internal class DifferenceViewerPreview : IDisposable
{
private IDifferenceViewer _viewer;
public DifferenceViewerPreview(IDifferenceViewer viewer)
{
Contract.ThrowIfNull(viewer);
_viewer = viewer;
}
public IDifferenceViewer Viewer => _viewer;
public void Dispose()
{
GC.SuppressFinalize(this);
if (_viewer != null && !_viewer.IsClosed)
{
_viewer.Close();
}
_viewer = null;
}
~DifferenceViewerPreview()
{
// make sure we are not leaking diff viewer
// we can't close the view from finalizer thread since it must be same
// thread (owner thread) this UI is created.
if (Environment.HasShutdownStarted)
{
return;
}
FatalError.ReportAndCatch(new Exception($"Dispose is not called how? viewer state : {_viewer.IsClosed}"));
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion
{
public class CompletionTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestGetCompletionsAsync_PromotesCommitCharactersToListAsync()
{
var clientCapabilities = new LSP.VSClientCapabilities
{
SupportsVisualStudioExtensions = true,
TextDocument = new LSP.TextDocumentClientCapabilities()
{
Completion = new LSP.VSCompletionSetting()
{
CompletionList = new LSP.VSCompletionListSetting()
{
CommitCharacters = true,
}
}
}
};
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" },
request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false);
var expectedCommitCharacters = expected.CommitCharacters;
// Null out the commit characters since we're expecting the commit characters will be lifted onto the completion list.
expected.CommitCharacters = null;
var results = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
var vsCompletionList = Assert.IsAssignableFrom<LSP.VSCompletionList>(results);
Assert.Equal(expectedCommitCharacters, vsCompletionList.CommitCharacters.Value.First);
}
[Fact]
public async Task TestGetCompletionsAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" },
request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
public async Task TestGetCompletionsTypingAsync()
{
var markup =
@"class A
{
void M()
{
A{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "A",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" },
request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
public async Task TestGetCompletionsDoesNotIncludeUnimportedTypesAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var solution = testLspServer.TestWorkspace.CurrentSolution;
// Make sure the unimported types option is on by default.
testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, true)
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, true));
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams);
Assert.False(results.Items.Any(item => "Console" == item.Label));
}
[Fact]
public async Task TestGetCompletionsDoesNotIncludeSnippetsAsync()
{
var markup =
@"class A
{
{|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var solution = testLspServer.TestWorkspace.CurrentSolution;
solution = solution.WithOptions(solution.Options
.WithChangedOption(CompletionOptions.SnippetsBehavior, LanguageNames.CSharp, SnippetsRule.AlwaysInclude));
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams);
Assert.False(results.Items.Any(item => "ctor" == item.Label));
}
[Fact]
public async Task TestGetCompletionsWithPreselectAsync()
{
var markup =
@"class A
{
void M()
{
A classA = new {|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" },
completionParams, document, preselect: true, commitCharacters: ImmutableArray.Create(' ', '(', '[', '{', ';', '.'),
insertText: "A").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
public async Task TestGetCompletionsIsInSuggestionMode()
{
var markup =
@"
using System.Collections.Generic;
using System.Linq;
namespace M
{
class Item
{
void M()
{
var items = new List<Item>();
items.Count(i{|caret:|}
}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "i",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = (LSP.VSCompletionList)await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.Items.Any());
Assert.True(results.SuggestionMode);
}
[Fact]
public async Task TestGetDateAndTimeCompletionsAsync()
{
var markup =
@"using System;
class A
{
void M()
{
DateTime.Now.ToString(""{|caret:|});
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "\"",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(
label: "d", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, insertText: "d", sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")]
public async Task TestGetRegexCompletionsAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
new Regex(""{|caret:|}"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var solution = testLspServer.GetCurrentSolution();
var document = solution.Projects.First().Documents.First();
// Set to use prototype completion behavior (i.e. feature flag).
var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true);
Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options)));
var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 19, endLine: 5, endChar: 19);
var expected = await CreateCompletionItemAsync(
label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit,
sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")]
public async Task TestGetRegexLiteralCompletionsAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
new Regex(@""\{|caret:|}"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\\",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var solution = testLspServer.GetCurrentSolution();
var document = solution.Projects.First().Documents.First();
// Set to use prototype completion behavior (i.e. feature flag).
var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true);
Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options)));
var textEdit = GenerateTextEdit(@"\A", startLine: 5, startChar: 20, endLine: 5, endChar: 21);
var expected = await CreateCompletionItemAsync(
label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit,
sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")]
public async Task TestGetRegexCompletionsReplaceTextAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
Regex r = new(""\\{|caret:|}"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "\\",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var solution = testLspServer.GetCurrentSolution();
var document = solution.Projects.First().Documents.First();
// Set to use prototype completion behavior (i.e. feature flag).
var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true);
Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options)));
var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 23, endLine: 5, endChar: 25);
var expected = await CreateCompletionItemAsync(
label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit,
sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(46694, "https://github.com/dotnet/roslyn/issues/46694")]
public async Task TestCompletionListCacheAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var cache = GetCompletionListCache(testLspServer);
Assert.NotNull(cache);
var testAccessor = cache.GetTestAccessor();
// This test assumes that the maximum cache size is 3, and will have to modified if this number changes.
Assert.True(CompletionListCache.TestAccessor.MaximumCacheSize == 3);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
// 1 item in cache
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
var completionList = cache.GetCachedCompletionList(0).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 1);
// 2 items in cache
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
completionList = cache.GetCachedCompletionList(0).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(1).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 2);
// 3 items in cache
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
completionList = cache.GetCachedCompletionList(0).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(1).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(2).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 3);
// Maximum size of cache (3) should not be exceeded - oldest item should be ejected
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
var cacheEntry = cache.GetCachedCompletionList(0);
Assert.Null(cacheEntry);
completionList = cache.GetCachedCompletionList(1).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(2).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(3).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 3);
}
[Fact]
public async Task TestGetCompletionsWithDeletionInvokeKindAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Deletion,
triggerCharacter: "M",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" },
completionParams, document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters).ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
// By default, completion doesn't trigger on deletion.
Assert.Null(results);
}
[Fact]
public async Task TestDoNotProvideOverrideTextEditsOrInsertTextAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Null(results.Items.First().TextEdit);
Assert.Null(results.Items.First().InsertText);
}
[Fact]
public async Task TestDoNotProvidePartialMethodTextEditsOrInsertTextAsync()
{
var markup =
@"partial class C
{
partial void Method();
}
partial class C
{
partial {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Null(results.Items.First().TextEdit);
Assert.Null(results.Items.First().InsertText);
}
[Fact]
public async Task TestAlwaysHasCommitCharactersWithoutVSCapabilityAsync()
{
var markup =
@"using System;
class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false);
Assert.NotNull(results);
Assert.NotEmpty(results.Items);
Assert.All(results.Items, (item) => Assert.NotNull(item.CommitCharacters));
}
[Fact]
public async Task TestSoftSelectedItemsHaveNoCommitCharactersWithoutVSCapabilityAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
new Regex(""[{|caret:|}"")
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "[",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false);
Assert.NotNull(results);
Assert.NotEmpty(results.Items);
Assert.All(results.Items, (item) => Assert.True(item.CommitCharacters.Length == 0));
}
[Fact]
public async Task TestLargeCompletionListIsMarkedIncompleteAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
}
[Fact]
public async Task TestIncompleteCompletionListContainsPreselectedItemAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
class W
{
}
void M()
{
W someW = new {|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: " ",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
var itemW = results.Items.Single(item => item.Label == "W");
Assert.True(itemW.Preselect);
}
[Fact]
public async Task TestRequestForIncompleteListIsFilteredDownAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
await testLspServer.OpenDocumentAsync(caretLocation.Uri);
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "a"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task TestIncompleteCompletionListFiltersWithPatternMatchingAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
await testLspServer.OpenDocumentAsync(caretLocation.Uri);
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "C"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "C",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("TaiwanCalendar", results.Items.First().Label);
}
[Fact]
public async Task TestIncompleteCompletionListWithDeletionAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
await testLspServer.OpenDocumentAsync(caretLocation.Uri);
// Insert 'T' to make 'T' and trigger completion.
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
// Insert 'ask' to make 'Task' and trigger completion.
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "ask"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "k",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("Task", results.Items.First().Label);
// Delete 'ask' to make 'T' and trigger completion on deletion.
await testLspServer.DeleteTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, caretLocation.Range.End.Line, caretLocation.Range.End.Character + 3));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Deletion,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
// Insert 'i' to make 'Ti' and trigger completion.
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "i"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "i",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("Timeout", results.Items.First().Label);
}
[Fact]
public async Task TestNewCompletionRequestDoesNotUseIncompleteListAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|firstCaret:|}
}
void M2()
{
Console.W{|secondCaret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var firstCaret = locations["firstCaret"].Single();
await testLspServer.OpenDocumentAsync(firstCaret.Uri);
// Make a completion request that returns an incomplete list.
var completionParams = CreateCompletionParams(
firstCaret,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
// Make a second completion request, but not for the original incomplete list.
completionParams = CreateCompletionParams(
locations["secondCaret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "W",
triggerKind: LSP.CompletionTriggerKind.Invoked);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.False(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("WindowHeight", results.Items.First().Label);
}
[Fact]
public async Task TestRequestForIncompleteListWhenMissingCachedListAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
Ta{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task TestRequestForIncompleteListUsesCorrectCachedListAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M1()
{
int Taaa = 1;
T{|firstCaret:|}
}
void M2()
{
int Saaa = 1;
{|secondCaret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var firstCaretLocation = locations["firstCaret"].Single();
await testLspServer.OpenDocumentAsync(firstCaretLocation.Uri);
// Create request to on insertion of 'T'
var completionParams = CreateCompletionParams(
firstCaretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
Assert.Single(results.Items, item => item.Label == "Taaa");
// Insert 'S' at the second caret
var secondCaretLocation = locations["secondCaret"].Single();
await testLspServer.InsertTextAsync(secondCaretLocation.Uri, (secondCaretLocation.Range.End.Line, secondCaretLocation.Range.End.Character, "S"));
// Trigger completion on 'S'
var triggerLocation = GetLocationPlusOne(secondCaretLocation);
completionParams = CreateCompletionParams(
triggerLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "S",
triggerKind: LSP.CompletionTriggerKind.Invoked);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("Saaa", results.Items.First().Label);
// Now type 'a' in M1 after 'T'
await testLspServer.InsertTextAsync(firstCaretLocation.Uri, (firstCaretLocation.Range.End.Line, firstCaretLocation.Range.End.Character, "a"));
// Trigger completion on 'a' (using incomplete as we previously returned incomplete completions from 'T').
triggerLocation = GetLocationPlusOne(firstCaretLocation);
completionParams = CreateCompletionParams(
triggerLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
// Verify we get completions for 'Ta' and not from the 'S' location in M2
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.DoesNotContain(results.Items, item => item.Label == "Saaa");
Assert.Contains(results.Items, item => item.Label == "Taaa");
static LSP.Location GetLocationPlusOne(LSP.Location originalLocation)
{
var newPosition = new LSP.Position { Character = originalLocation.Range.Start.Character + 1, Line = originalLocation.Range.Start.Line };
return new LSP.Location
{
Uri = originalLocation.Uri,
Range = new LSP.Range { Start = newPosition, End = newPosition }
};
}
}
[Fact]
public async Task TestCompletionRequestRespectsListSizeOptionAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var listMaxSize = 1;
testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options.WithChangedOption(LspOptions.MaxCompletionListSize, listMaxSize));
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.Equal(listMaxSize, results.Items.Length);
}
private static Task<LSP.CompletionList> RunGetCompletionsAsync(TestLspServer testLspServer, LSP.CompletionParams completionParams)
{
var clientCapabilities = new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true };
return RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities);
}
private static async Task<LSP.CompletionList> RunGetCompletionsAsync(
TestLspServer testLspServer,
LSP.CompletionParams completionParams,
LSP.VSClientCapabilities clientCapabilities)
{
return await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName,
completionParams, clientCapabilities, null, CancellationToken.None);
}
private static CompletionListCache GetCompletionListCache(TestLspServer testLspServer)
{
var dispatchAccessor = testLspServer.GetDispatcherAccessor();
var handler = (CompletionHandler)dispatchAccessor.GetHandler<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName);
Assert.NotNull(handler);
return handler.GetTestAccessor().GetCache();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion
{
public class CompletionTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task TestGetCompletionsAsync_PromotesCommitCharactersToListAsync()
{
var clientCapabilities = new LSP.VSClientCapabilities
{
SupportsVisualStudioExtensions = true,
TextDocument = new LSP.TextDocumentClientCapabilities()
{
Completion = new LSP.VSCompletionSetting()
{
CompletionList = new LSP.VSCompletionListSetting()
{
CommitCharacters = true,
}
}
}
};
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" },
request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false);
var expectedCommitCharacters = expected.CommitCharacters;
// Null out the commit characters since we're expecting the commit characters will be lifted onto the completion list.
expected.CommitCharacters = null;
var results = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
var vsCompletionList = Assert.IsAssignableFrom<LSP.VSCompletionList>(results);
Assert.Equal(expectedCommitCharacters, vsCompletionList.CommitCharacters.Value.First);
}
[Fact]
public async Task TestGetCompletionsAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" },
request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
public async Task TestGetCompletionsTypingAsync()
{
var markup =
@"class A
{
void M()
{
A{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "A",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(label: "A", kind: LSP.CompletionItemKind.Class, tags: new string[] { "Class", "Internal" },
request: completionParams, document: document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters, insertText: "A").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
public async Task TestGetCompletionsDoesNotIncludeUnimportedTypesAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var solution = testLspServer.TestWorkspace.CurrentSolution;
// Make sure the unimported types option is on by default.
testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, true)
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, true));
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams);
Assert.False(results.Items.Any(item => "Console" == item.Label));
}
[Fact]
public async Task TestGetCompletionsDoesNotIncludeSnippetsAsync()
{
var markup =
@"class A
{
{|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var solution = testLspServer.TestWorkspace.CurrentSolution;
solution = solution.WithOptions(solution.Options
.WithChangedOption(CompletionOptions.SnippetsBehavior, LanguageNames.CSharp, SnippetsRule.AlwaysInclude));
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams);
Assert.False(results.Items.Any(item => "ctor" == item.Label));
}
[Fact]
public async Task TestGetCompletionsWithPreselectAsync()
{
var markup =
@"class A
{
void M()
{
A classA = new {|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" },
completionParams, document, preselect: true, commitCharacters: ImmutableArray.Create(' ', '(', '[', '{', ';', '.'),
insertText: "A").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
public async Task TestGetCompletionsIsInSuggestionMode()
{
var markup =
@"
using System.Collections.Generic;
using System.Linq;
namespace M
{
class Item
{
void M()
{
var items = new List<Item>();
items.Count(i{|caret:|}
}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "i",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = (LSP.VSCompletionList)await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.Items.Any());
Assert.True(results.SuggestionMode);
}
[Fact]
public async Task TestGetDateAndTimeCompletionsAsync()
{
var markup =
@"using System;
class A
{
void M()
{
DateTime.Now.ToString(""{|caret:|});
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "\"",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync(
label: "d", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, insertText: "d", sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")]
public async Task TestGetRegexCompletionsAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
new Regex(""{|caret:|}"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var solution = testLspServer.GetCurrentSolution();
var document = solution.Projects.First().Documents.First();
// Set to use prototype completion behavior (i.e. feature flag).
var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true);
Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options)));
var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 19, endLine: 5, endChar: 19);
var expected = await CreateCompletionItemAsync(
label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit,
sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")]
public async Task TestGetRegexLiteralCompletionsAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
new Regex(@""\{|caret:|}"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\\",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var solution = testLspServer.GetCurrentSolution();
var document = solution.Projects.First().Documents.First();
// Set to use prototype completion behavior (i.e. feature flag).
var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true);
Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options)));
var textEdit = GenerateTextEdit(@"\A", startLine: 5, startChar: 20, endLine: 5, endChar: 21);
var expected = await CreateCompletionItemAsync(
label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit,
sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(50964, "https://github.com/dotnet/roslyn/issues/50964")]
public async Task TestGetRegexCompletionsReplaceTextAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
Regex r = new(""\\{|caret:|}"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "\\",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var solution = testLspServer.GetCurrentSolution();
var document = solution.Projects.First().Documents.First();
// Set to use prototype completion behavior (i.e. feature flag).
var options = solution.Workspace.Options.WithChangedOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, LanguageNames.CSharp, true);
Assert.True(solution.Workspace.TryApplyChanges(solution.WithOptions(options)));
var textEdit = GenerateTextEdit(@"\\A", startLine: 5, startChar: 23, endLine: 5, endChar: 25);
var expected = await CreateCompletionItemAsync(
label: @"\A", kind: LSP.CompletionItemKind.Text, tags: new string[] { "Text" }, request: completionParams, document: document, textEdit: textEdit,
sortText: "0000").ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
AssertJsonEquals(expected, results.Items.First());
}
[Fact]
[WorkItem(46694, "https://github.com/dotnet/roslyn/issues/46694")]
public async Task TestCompletionListCacheAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var cache = GetCompletionListCache(testLspServer);
Assert.NotNull(cache);
var testAccessor = cache.GetTestAccessor();
// This test assumes that the maximum cache size is 3, and will have to modified if this number changes.
Assert.True(CompletionListCache.TestAccessor.MaximumCacheSize == 3);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
// 1 item in cache
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
var completionList = cache.GetCachedCompletionList(0).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 1);
// 2 items in cache
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
completionList = cache.GetCachedCompletionList(0).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(1).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 2);
// 3 items in cache
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
completionList = cache.GetCachedCompletionList(0).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(1).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(2).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 3);
// Maximum size of cache (3) should not be exceeded - oldest item should be ejected
await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
var cacheEntry = cache.GetCachedCompletionList(0);
Assert.Null(cacheEntry);
completionList = cache.GetCachedCompletionList(1).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(2).CompletionList;
Assert.NotNull(completionList);
completionList = cache.GetCachedCompletionList(3).CompletionList;
Assert.NotNull(completionList);
Assert.True(testAccessor.GetCacheContents().Count == 3);
}
[Fact]
public async Task TestGetCompletionsWithDeletionInvokeKindAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Deletion,
triggerCharacter: "M",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var expected = await CreateCompletionItemAsync("A", LSP.CompletionItemKind.Class, new string[] { "Class", "Internal" },
completionParams, document, commitCharacters: CompletionRules.Default.DefaultCommitCharacters).ConfigureAwait(false);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
// By default, completion doesn't trigger on deletion.
Assert.Null(results);
}
[Fact]
public async Task TestDoNotProvideOverrideTextEditsOrInsertTextAsync()
{
var markup =
@"abstract class A
{
public abstract void M();
}
class B : A
{
override {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Null(results.Items.First().TextEdit);
Assert.Null(results.Items.First().InsertText);
}
[Fact]
public async Task TestDoNotProvidePartialMethodTextEditsOrInsertTextAsync()
{
var markup =
@"partial class C
{
partial void Method();
}
partial class C
{
partial {|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Null(results.Items.First().TextEdit);
Assert.Null(results.Items.First().InsertText);
}
[Fact]
public async Task TestAlwaysHasCommitCharactersWithoutVSCapabilityAsync()
{
var markup =
@"using System;
class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false);
Assert.NotNull(results);
Assert.NotEmpty(results.Items);
Assert.All(results.Items, (item) => Assert.NotNull(item.CommitCharacters));
}
[Fact]
public async Task TestSoftSelectedItemsHaveNoCommitCharactersWithoutVSCapabilityAsync()
{
var markup =
@"using System.Text.RegularExpressions;
class A
{
void M()
{
new Regex(""[{|caret:|}"")
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "[",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First();
var results = await RunGetCompletionsAsync(testLspServer, completionParams, new LSP.VSClientCapabilities()).ConfigureAwait(false);
Assert.NotNull(results);
Assert.NotEmpty(results.Items);
Assert.All(results.Items, (item) => Assert.True(item.CommitCharacters.Length == 0));
}
[Fact]
public async Task TestLargeCompletionListIsMarkedIncompleteAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
}
[Fact]
public async Task TestIncompleteCompletionListContainsPreselectedItemAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
class W
{
}
void M()
{
W someW = new {|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: " ",
triggerKind: LSP.CompletionTriggerKind.TriggerCharacter);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
var itemW = results.Items.Single(item => item.Label == "W");
Assert.True(itemW.Preselect);
}
[Fact]
public async Task TestRequestForIncompleteListIsFilteredDownAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
await testLspServer.OpenDocumentAsync(caretLocation.Uri);
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "a"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task TestIncompleteCompletionListFiltersWithPatternMatchingAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
await testLspServer.OpenDocumentAsync(caretLocation.Uri);
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "C"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "C",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("TaiwanCalendar", results.Items.First().Label);
}
[Fact]
public async Task TestIncompleteCompletionListWithDeletionAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
await testLspServer.OpenDocumentAsync(caretLocation.Uri);
// Insert 'T' to make 'T' and trigger completion.
var completionParams = CreateCompletionParams(
caretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
// Insert 'ask' to make 'Task' and trigger completion.
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "ask"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "k",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("Task", results.Items.First().Label);
// Delete 'ask' to make 'T' and trigger completion on deletion.
await testLspServer.DeleteTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, caretLocation.Range.End.Line, caretLocation.Range.End.Character + 3));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Deletion,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
// Insert 'i' to make 'Ti' and trigger completion.
await testLspServer.InsertTextAsync(caretLocation.Uri, (caretLocation.Range.End.Line, caretLocation.Range.End.Character, "i"));
completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "i",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("Timeout", results.Items.First().Label);
}
[Fact]
public async Task TestNewCompletionRequestDoesNotUseIncompleteListAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
T{|firstCaret:|}
}
void M2()
{
Console.W{|secondCaret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var firstCaret = locations["firstCaret"].Single();
await testLspServer.OpenDocumentAsync(firstCaret.Uri);
// Make a completion request that returns an incomplete list.
var completionParams = CreateCompletionParams(
firstCaret,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
// Make a second completion request, but not for the original incomplete list.
completionParams = CreateCompletionParams(
locations["secondCaret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "W",
triggerKind: LSP.CompletionTriggerKind.Invoked);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.False(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Equal("WindowHeight", results.Items.First().Label);
}
[Fact]
public async Task TestRequestForIncompleteListWhenMissingCachedListAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M()
{
Ta{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].Single();
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.Contains("ta", results.Items.First().Label, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task TestRequestForIncompleteListUsesCorrectCachedListAsync()
{
var markup =
@"using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class A
{
void M1()
{
int Taaa = 1;
T{|firstCaret:|}
}
void M2()
{
int Saaa = 1;
{|secondCaret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var firstCaretLocation = locations["firstCaret"].Single();
await testLspServer.OpenDocumentAsync(firstCaretLocation.Uri);
// Create request to on insertion of 'T'
var completionParams = CreateCompletionParams(
firstCaretLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "T",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("T", results.Items.First().Label);
Assert.Single(results.Items, item => item.Label == "Taaa");
// Insert 'S' at the second caret
var secondCaretLocation = locations["secondCaret"].Single();
await testLspServer.InsertTextAsync(secondCaretLocation.Uri, (secondCaretLocation.Range.End.Line, secondCaretLocation.Range.End.Character, "S"));
// Trigger completion on 'S'
var triggerLocation = GetLocationPlusOne(secondCaretLocation);
completionParams = CreateCompletionParams(
triggerLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "S",
triggerKind: LSP.CompletionTriggerKind.Invoked);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.Equal(1000, results.Items.Length);
Assert.True(results.IsIncomplete);
Assert.Equal("Saaa", results.Items.First().Label);
// Now type 'a' in M1 after 'T'
await testLspServer.InsertTextAsync(firstCaretLocation.Uri, (firstCaretLocation.Range.End.Line, firstCaretLocation.Range.End.Character, "a"));
// Trigger completion on 'a' (using incomplete as we previously returned incomplete completions from 'T').
triggerLocation = GetLocationPlusOne(firstCaretLocation);
completionParams = CreateCompletionParams(
triggerLocation,
invokeKind: LSP.VSCompletionInvokeKind.Typing,
triggerCharacter: "a",
triggerKind: LSP.CompletionTriggerKind.TriggerForIncompleteCompletions);
results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
// Verify we get completions for 'Ta' and not from the 'S' location in M2
Assert.True(results.IsIncomplete);
Assert.True(results.Items.Length < 1000);
Assert.DoesNotContain(results.Items, item => item.Label == "Saaa");
Assert.Contains(results.Items, item => item.Label == "Taaa");
static LSP.Location GetLocationPlusOne(LSP.Location originalLocation)
{
var newPosition = new LSP.Position { Character = originalLocation.Range.Start.Character + 1, Line = originalLocation.Range.Start.Line };
return new LSP.Location
{
Uri = originalLocation.Uri,
Range = new LSP.Range { Start = newPosition, End = newPosition }
};
}
}
[Fact]
public async Task TestCompletionRequestRespectsListSizeOptionAsync()
{
var markup =
@"class A
{
void M()
{
{|caret:|}
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var completionParams = CreateCompletionParams(
locations["caret"].Single(),
invokeKind: LSP.VSCompletionInvokeKind.Explicit,
triggerCharacter: "\0",
triggerKind: LSP.CompletionTriggerKind.Invoked);
var listMaxSize = 1;
testLspServer.TestWorkspace.SetOptions(testLspServer.TestWorkspace.CurrentSolution.Options.WithChangedOption(LspOptions.MaxCompletionListSize, listMaxSize));
var results = await RunGetCompletionsAsync(testLspServer, completionParams).ConfigureAwait(false);
Assert.True(results.IsIncomplete);
Assert.Equal(listMaxSize, results.Items.Length);
}
private static Task<LSP.CompletionList> RunGetCompletionsAsync(TestLspServer testLspServer, LSP.CompletionParams completionParams)
{
var clientCapabilities = new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true };
return RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities);
}
private static async Task<LSP.CompletionList> RunGetCompletionsAsync(
TestLspServer testLspServer,
LSP.CompletionParams completionParams,
LSP.VSClientCapabilities clientCapabilities)
{
return await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName,
completionParams, clientCapabilities, null, CancellationToken.None);
}
private static CompletionListCache GetCompletionListCache(TestLspServer testLspServer)
{
var dispatchAccessor = testLspServer.GetDispatcherAccessor();
var handler = (CompletionHandler)dispatchAccessor.GetHandler<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName);
Assert.NotNull(handler);
return handler.GetTestAccessor().GetCache();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Symbols/Attributes/ObsoleteAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
internal enum ObsoleteAttributeKind
{
None,
Uninitialized,
Obsolete,
Deprecated,
Experimental,
}
/// <summary>
/// Information decoded from <see cref="ObsoleteAttribute"/>.
/// </summary>
internal sealed class ObsoleteAttributeData
{
public static readonly ObsoleteAttributeData Uninitialized = new ObsoleteAttributeData(ObsoleteAttributeKind.Uninitialized, message: null, isError: false, diagnosticId: null, urlFormat: null);
public static readonly ObsoleteAttributeData Experimental = new ObsoleteAttributeData(ObsoleteAttributeKind.Experimental, message: null, isError: false, diagnosticId: null, urlFormat: null);
public const string DiagnosticIdPropertyName = "DiagnosticId";
public const string UrlFormatPropertyName = "UrlFormat";
public ObsoleteAttributeData(ObsoleteAttributeKind kind, string? message, bool isError, string? diagnosticId, string? urlFormat)
{
Kind = kind;
Message = message;
IsError = isError;
DiagnosticId = diagnosticId;
UrlFormat = urlFormat;
}
public readonly ObsoleteAttributeKind Kind;
/// <summary>
/// True if an error should be thrown for the <see cref="ObsoleteAttribute"/>. Default is false in which case
/// a warning is thrown.
/// </summary>
public readonly bool IsError;
/// <summary>
/// The message that will be shown when an error/warning is created for <see cref="ObsoleteAttribute"/>.
/// </summary>
public readonly string? Message;
/// <summary>
/// The custom diagnostic ID to use for obsolete diagnostics.
/// If null, diagnostics are produced using the compiler default diagnostic IDs.
/// </summary>
public readonly string? DiagnosticId;
/// <summary>
/// <para>
/// The custom help URL format string for obsolete diagnostics.
/// Expected to contain zero or one format items.
/// </para>
/// <para>
/// When specified, the obsolete diagnostic's <see cref="DiagnosticDescriptor.HelpLinkUri"/> will be produced
/// by formatting this string using the <see cref="DiagnosticId"/> as the single argument.
/// </para>
///
/// <example>
/// e.g. with a <see cref="DiagnosticId"/> value <c>"TEST1"</c>,
/// and a <see cref="UrlFormat"/> value <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/{0}/"/>,<br/>
/// the diagnostic will have the HelpLinkUri <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/TEST1/"/>.
/// </example>
/// </summary>
public readonly string? UrlFormat;
internal bool IsUninitialized
{
get { return ReferenceEquals(this, Uninitialized); }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
internal enum ObsoleteAttributeKind
{
None,
Uninitialized,
Obsolete,
Deprecated,
Experimental,
}
/// <summary>
/// Information decoded from <see cref="ObsoleteAttribute"/>.
/// </summary>
internal sealed class ObsoleteAttributeData
{
public static readonly ObsoleteAttributeData Uninitialized = new ObsoleteAttributeData(ObsoleteAttributeKind.Uninitialized, message: null, isError: false, diagnosticId: null, urlFormat: null);
public static readonly ObsoleteAttributeData Experimental = new ObsoleteAttributeData(ObsoleteAttributeKind.Experimental, message: null, isError: false, diagnosticId: null, urlFormat: null);
public const string DiagnosticIdPropertyName = "DiagnosticId";
public const string UrlFormatPropertyName = "UrlFormat";
public ObsoleteAttributeData(ObsoleteAttributeKind kind, string? message, bool isError, string? diagnosticId, string? urlFormat)
{
Kind = kind;
Message = message;
IsError = isError;
DiagnosticId = diagnosticId;
UrlFormat = urlFormat;
}
public readonly ObsoleteAttributeKind Kind;
/// <summary>
/// True if an error should be thrown for the <see cref="ObsoleteAttribute"/>. Default is false in which case
/// a warning is thrown.
/// </summary>
public readonly bool IsError;
/// <summary>
/// The message that will be shown when an error/warning is created for <see cref="ObsoleteAttribute"/>.
/// </summary>
public readonly string? Message;
/// <summary>
/// The custom diagnostic ID to use for obsolete diagnostics.
/// If null, diagnostics are produced using the compiler default diagnostic IDs.
/// </summary>
public readonly string? DiagnosticId;
/// <summary>
/// <para>
/// The custom help URL format string for obsolete diagnostics.
/// Expected to contain zero or one format items.
/// </para>
/// <para>
/// When specified, the obsolete diagnostic's <see cref="DiagnosticDescriptor.HelpLinkUri"/> will be produced
/// by formatting this string using the <see cref="DiagnosticId"/> as the single argument.
/// </para>
///
/// <example>
/// e.g. with a <see cref="DiagnosticId"/> value <c>"TEST1"</c>,
/// and a <see cref="UrlFormat"/> value <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/{0}/"/>,<br/>
/// the diagnostic will have the HelpLinkUri <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/TEST1/"/>.
/// </example>
/// </summary>
public readonly string? UrlFormat;
internal bool IsUninitialized
{
get { return ReferenceEquals(this, Uninitialized); }
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ExpressionSyntaxExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class ExpressionSyntaxExtensions
{
public static ExpressionSyntax Parenthesize(
this ExpressionSyntax expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
// a 'ref' expression should never be parenthesized. It fundamentally breaks the code.
// This is because, from the language's perspective there is no such thing as a ref
// expression. instead, there are constructs like ```return ref expr``` or
// ```x ? ref expr1 : ref expr2```, or ```ref int a = ref expr``` in these cases, the
// ref's do not belong to the exprs, but instead belong to the parent construct. i.e.
// ```return ref``` or ``` ? ref ... : ref ... ``` or ``` ... = ref ...```. For
// parsing convenience, and to prevent having to update all these constructs, we settled
// on a ref-expression node. But this node isn't a true expression that be operated
// on like with everything else.
if (expression.IsKind(SyntaxKind.RefExpression))
{
return expression;
}
// Throw expressions are not permitted to be parenthesized:
//
// "a" ?? throw new ArgumentNullException()
//
// is legal whereas
//
// "a" ?? (throw new ArgumentNullException())
//
// is not.
if (expression.IsKind(SyntaxKind.ThrowExpression))
{
return expression;
}
var result = ParenthesizeWorker(expression, includeElasticTrivia);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
private static ExpressionSyntax ParenthesizeWorker(
this ExpressionSyntax expression, bool includeElasticTrivia)
{
var withoutTrivia = expression.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedExpression(withoutTrivia)
: SyntaxFactory.ParenthesizedExpression(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
return parenthesized.WithTriviaFrom(expression);
}
public static PatternSyntax Parenthesize(
this PatternSyntax pattern, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
var withoutTrivia = pattern.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedPattern(withoutTrivia)
: SyntaxFactory.ParenthesizedPattern(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
var result = parenthesized.WithTriviaFrom(pattern);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
public static CastExpressionSyntax Cast(
this ExpressionSyntax expression,
ITypeSymbol targetType)
{
var parenthesized = expression.Parenthesize();
var castExpression = SyntaxFactory.CastExpression(
targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized);
return castExpression.WithAdditionalAnnotations(Simplifier.Annotation);
}
/// <summary>
/// Adds to <paramref name="targetType"/> if it does not contain an anonymous
/// type and binds to the same type at the given <paramref name="position"/>.
/// </summary>
public static ExpressionSyntax CastIfPossible(
this ExpressionSyntax expression,
ITypeSymbol targetType,
int position,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (targetType.ContainsAnonymousType())
{
return expression;
}
if (targetType.Kind == SymbolKind.DynamicType)
{
targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}
var typeSyntax = targetType.GenerateTypeSyntax();
var type = semanticModel.GetSpeculativeTypeInfo(
position,
typeSyntax,
SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
if (!targetType.Equals(type))
{
return expression;
}
var castExpression = expression.Cast(targetType);
// Ensure that inserting the cast doesn't change the semantics.
var specAnalyzer = new SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken);
var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel;
if (speculativeSemanticModel == null)
{
return expression;
}
var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression;
if (!CastSimplifier.IsUnnecessaryCast(speculatedCastExpression, speculativeSemanticModel, cancellationToken))
{
return expression;
}
return castExpression;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class ExpressionSyntaxExtensions
{
public static ExpressionSyntax Parenthesize(
this ExpressionSyntax expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
// a 'ref' expression should never be parenthesized. It fundamentally breaks the code.
// This is because, from the language's perspective there is no such thing as a ref
// expression. instead, there are constructs like ```return ref expr``` or
// ```x ? ref expr1 : ref expr2```, or ```ref int a = ref expr``` in these cases, the
// ref's do not belong to the exprs, but instead belong to the parent construct. i.e.
// ```return ref``` or ``` ? ref ... : ref ... ``` or ``` ... = ref ...```. For
// parsing convenience, and to prevent having to update all these constructs, we settled
// on a ref-expression node. But this node isn't a true expression that be operated
// on like with everything else.
if (expression.IsKind(SyntaxKind.RefExpression))
{
return expression;
}
// Throw expressions are not permitted to be parenthesized:
//
// "a" ?? throw new ArgumentNullException()
//
// is legal whereas
//
// "a" ?? (throw new ArgumentNullException())
//
// is not.
if (expression.IsKind(SyntaxKind.ThrowExpression))
{
return expression;
}
var result = ParenthesizeWorker(expression, includeElasticTrivia);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
private static ExpressionSyntax ParenthesizeWorker(
this ExpressionSyntax expression, bool includeElasticTrivia)
{
var withoutTrivia = expression.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedExpression(withoutTrivia)
: SyntaxFactory.ParenthesizedExpression(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
return parenthesized.WithTriviaFrom(expression);
}
public static PatternSyntax Parenthesize(
this PatternSyntax pattern, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true)
{
var withoutTrivia = pattern.WithoutTrivia();
var parenthesized = includeElasticTrivia
? SyntaxFactory.ParenthesizedPattern(withoutTrivia)
: SyntaxFactory.ParenthesizedPattern(
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty),
withoutTrivia,
SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty));
var result = parenthesized.WithTriviaFrom(pattern);
return addSimplifierAnnotation
? result.WithAdditionalAnnotations(Simplifier.Annotation)
: result;
}
public static CastExpressionSyntax Cast(
this ExpressionSyntax expression,
ITypeSymbol targetType)
{
var parenthesized = expression.Parenthesize();
var castExpression = SyntaxFactory.CastExpression(
targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized);
return castExpression.WithAdditionalAnnotations(Simplifier.Annotation);
}
/// <summary>
/// Adds to <paramref name="targetType"/> if it does not contain an anonymous
/// type and binds to the same type at the given <paramref name="position"/>.
/// </summary>
public static ExpressionSyntax CastIfPossible(
this ExpressionSyntax expression,
ITypeSymbol targetType,
int position,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (targetType.ContainsAnonymousType())
{
return expression;
}
if (targetType.Kind == SymbolKind.DynamicType)
{
targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}
var typeSyntax = targetType.GenerateTypeSyntax();
var type = semanticModel.GetSpeculativeTypeInfo(
position,
typeSyntax,
SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
if (!targetType.Equals(type))
{
return expression;
}
var castExpression = expression.Cast(targetType);
// Ensure that inserting the cast doesn't change the semantics.
var specAnalyzer = new SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken);
var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel;
if (speculativeSemanticModel == null)
{
return expression;
}
var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression;
if (!CastSimplifier.IsUnnecessaryCast(speculatedCastExpression, speculativeSemanticModel, cancellationToken))
{
return expression;
}
return castExpression;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Completion/Providers/AbstractEmbeddedLanguageCompletionProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.Features.EmbeddedLanguages;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
/// <summary>
/// The singular completion provider that will hook into completion and will
/// provider all completions across all embedded languages.
///
/// Completions for an individual language are provided by
/// <see cref="IEmbeddedLanguageFeatures.CompletionProvider"/>.
/// </summary>
internal abstract class AbstractEmbeddedLanguageCompletionProvider : LSPCompletionProvider
{
public const string EmbeddedProviderName = "EmbeddedProvider";
private ImmutableArray<IEmbeddedLanguage> _languageProviders;
protected AbstractEmbeddedLanguageCompletionProvider(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices, string languageName)
{
var embeddedLanguageServiceType = typeof(IEmbeddedLanguagesProvider).AssemblyQualifiedName;
TriggerCharacters = languageServices
.Where(lazyLanguageService => IsEmbeddedLanguageProvider(lazyLanguageService, languageName, embeddedLanguageServiceType))
.SelectMany(lazyLanguageService => ((IEmbeddedLanguagesProvider)lazyLanguageService.Value).Languages)
.SelectMany(GetTriggerCharactersForEmbeddedLanguage)
.ToImmutableHashSet();
}
private static ImmutableHashSet<char> GetTriggerCharactersForEmbeddedLanguage(IEmbeddedLanguage language)
{
var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider;
if (completionProvider is LSPCompletionProvider lspCompletionProvider)
{
return lspCompletionProvider.TriggerCharacters;
}
return ImmutableHashSet<char>.Empty;
}
private static bool IsEmbeddedLanguageProvider(Lazy<ILanguageService, LanguageServiceMetadata> lazyLanguageService, string languageName, string? embeddedLanguageServiceType)
{
return lazyLanguageService.Metadata.Language == languageName && lazyLanguageService.Metadata.ServiceType == embeddedLanguageServiceType;
}
protected ImmutableArray<IEmbeddedLanguage> GetLanguageProviders(HostLanguageServices? languageServices)
{
if (_languageProviders.IsDefault)
{
var languagesProvider = languageServices?.GetService<IEmbeddedLanguagesProvider>();
ImmutableInterlocked.InterlockedInitialize(ref _languageProviders, languagesProvider?.Languages ?? ImmutableArray<IEmbeddedLanguage>.Empty);
}
return _languageProviders;
}
public override ImmutableHashSet<char> TriggerCharacters { get; }
internal override bool ShouldTriggerCompletion(HostLanguageServices? languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options)
{
foreach (var language in GetLanguageProviders(languageServices))
{
var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider;
if (completionProvider != null)
{
if (completionProvider.ShouldTriggerCompletion(
text, caretPosition, trigger, options))
{
return true;
}
}
}
return false;
}
public override async Task ProvideCompletionsAsync(CompletionContext context)
{
foreach (var language in GetLanguageProviders(context.Document.Project.LanguageServices))
{
var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider;
if (completionProvider != null)
{
var count = context.Items.Count;
await completionProvider.ProvideCompletionsAsync(context).ConfigureAwait(false);
if (context.Items.Count > count)
{
return;
}
}
}
}
public override Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken)
=> GetLanguage(item).CompletionProvider.GetChangeAsync(document, item, commitKey, cancellationToken);
public override Task<CompletionDescription?> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
=> GetLanguage(item).CompletionProvider.GetDescriptionAsync(document, item, cancellationToken);
private IEmbeddedLanguageFeatures GetLanguage(CompletionItem item)
{
if (_languageProviders.IsDefault)
throw ExceptionUtilities.Unreachable;
return (IEmbeddedLanguageFeatures)_languageProviders.Single(lang => (lang as IEmbeddedLanguageFeatures)?.CompletionProvider?.Name == item.Properties[EmbeddedProviderName]);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.Features.EmbeddedLanguages;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
/// <summary>
/// The singular completion provider that will hook into completion and will
/// provider all completions across all embedded languages.
///
/// Completions for an individual language are provided by
/// <see cref="IEmbeddedLanguageFeatures.CompletionProvider"/>.
/// </summary>
internal abstract class AbstractEmbeddedLanguageCompletionProvider : LSPCompletionProvider
{
public const string EmbeddedProviderName = "EmbeddedProvider";
private ImmutableArray<IEmbeddedLanguage> _languageProviders;
protected AbstractEmbeddedLanguageCompletionProvider(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> languageServices, string languageName)
{
var embeddedLanguageServiceType = typeof(IEmbeddedLanguagesProvider).AssemblyQualifiedName;
TriggerCharacters = languageServices
.Where(lazyLanguageService => IsEmbeddedLanguageProvider(lazyLanguageService, languageName, embeddedLanguageServiceType))
.SelectMany(lazyLanguageService => ((IEmbeddedLanguagesProvider)lazyLanguageService.Value).Languages)
.SelectMany(GetTriggerCharactersForEmbeddedLanguage)
.ToImmutableHashSet();
}
private static ImmutableHashSet<char> GetTriggerCharactersForEmbeddedLanguage(IEmbeddedLanguage language)
{
var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider;
if (completionProvider is LSPCompletionProvider lspCompletionProvider)
{
return lspCompletionProvider.TriggerCharacters;
}
return ImmutableHashSet<char>.Empty;
}
private static bool IsEmbeddedLanguageProvider(Lazy<ILanguageService, LanguageServiceMetadata> lazyLanguageService, string languageName, string? embeddedLanguageServiceType)
{
return lazyLanguageService.Metadata.Language == languageName && lazyLanguageService.Metadata.ServiceType == embeddedLanguageServiceType;
}
protected ImmutableArray<IEmbeddedLanguage> GetLanguageProviders(HostLanguageServices? languageServices)
{
if (_languageProviders.IsDefault)
{
var languagesProvider = languageServices?.GetService<IEmbeddedLanguagesProvider>();
ImmutableInterlocked.InterlockedInitialize(ref _languageProviders, languagesProvider?.Languages ?? ImmutableArray<IEmbeddedLanguage>.Empty);
}
return _languageProviders;
}
public override ImmutableHashSet<char> TriggerCharacters { get; }
internal override bool ShouldTriggerCompletion(HostLanguageServices? languageServices, SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options)
{
foreach (var language in GetLanguageProviders(languageServices))
{
var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider;
if (completionProvider != null)
{
if (completionProvider.ShouldTriggerCompletion(
text, caretPosition, trigger, options))
{
return true;
}
}
}
return false;
}
public override async Task ProvideCompletionsAsync(CompletionContext context)
{
foreach (var language in GetLanguageProviders(context.Document.Project.LanguageServices))
{
var completionProvider = (language as IEmbeddedLanguageFeatures)?.CompletionProvider;
if (completionProvider != null)
{
var count = context.Items.Count;
await completionProvider.ProvideCompletionsAsync(context).ConfigureAwait(false);
if (context.Items.Count > count)
{
return;
}
}
}
}
public override Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken)
=> GetLanguage(item).CompletionProvider.GetChangeAsync(document, item, commitKey, cancellationToken);
public override Task<CompletionDescription?> GetDescriptionAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
=> GetLanguage(item).CompletionProvider.GetDescriptionAsync(document, item, cancellationToken);
private IEmbeddedLanguageFeatures GetLanguage(CompletionItem item)
{
if (_languageProviders.IsDefault)
throw ExceptionUtilities.Unreachable;
return (IEmbeddedLanguageFeatures)_languageProviders.Single(lang => (lang as IEmbeddedLanguageFeatures)?.CompletionProvider?.Name == item.Properties[EmbeddedProviderName]);
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Analyzers/UsePatternMatching/CSharpUseNotPatternDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching
{
/// <summary>
/// Looks for code of the forms:
///
/// var x = o as Type;
/// if (!(x is Y y)) ...
///
/// and converts it to:
///
/// if (x is not Y y) ...
///
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal partial class CSharpUseNotPatternDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseNotPatternDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseNotPatternDiagnosticId,
EnforceOnBuildValues.UseNotPattern,
CSharpCodeStyleOptions.PreferNotPattern,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(context =>
{
// "x is not Type y" is only available in C# 9.0 and above. Don't offer this refactoring
// in projects targeting a lesser version.
if (!((CSharpCompilation)context.Compilation).LanguageVersion.IsCSharp9OrAbove())
return;
context.RegisterSyntaxNodeAction(n => SyntaxNodeAction(n), SyntaxKind.LogicalNotExpression);
});
}
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
var node = syntaxContext.Node;
var syntaxTree = node.SyntaxTree;
var options = syntaxContext.Options;
var cancellationToken = syntaxContext.CancellationToken;
// Bail immediately if the user has disabled this feature.
var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferNotPattern, syntaxTree, cancellationToken);
if (!styleOption.Value)
return;
// Look for the form: !(x is Y y)
if (!(node is PrefixUnaryExpressionSyntax
{
Operand: ParenthesizedExpressionSyntax
{
Expression: IsPatternExpressionSyntax
{
Pattern: DeclarationPatternSyntax,
} isPattern,
},
} notExpression))
{
return;
}
// Put a diagnostic with the appropriate severity on `is` keyword.
syntaxContext.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
isPattern.IsKeyword.GetLocation(),
styleOption.Notification.Severity,
ImmutableArray.Create(notExpression.GetLocation()),
properties: null));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching
{
/// <summary>
/// Looks for code of the forms:
///
/// var x = o as Type;
/// if (!(x is Y y)) ...
///
/// and converts it to:
///
/// if (x is not Y y) ...
///
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal partial class CSharpUseNotPatternDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseNotPatternDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseNotPatternDiagnosticId,
EnforceOnBuildValues.UseNotPattern,
CSharpCodeStyleOptions.PreferNotPattern,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(context =>
{
// "x is not Type y" is only available in C# 9.0 and above. Don't offer this refactoring
// in projects targeting a lesser version.
if (!((CSharpCompilation)context.Compilation).LanguageVersion.IsCSharp9OrAbove())
return;
context.RegisterSyntaxNodeAction(n => SyntaxNodeAction(n), SyntaxKind.LogicalNotExpression);
});
}
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
var node = syntaxContext.Node;
var syntaxTree = node.SyntaxTree;
var options = syntaxContext.Options;
var cancellationToken = syntaxContext.CancellationToken;
// Bail immediately if the user has disabled this feature.
var styleOption = options.GetOption(CSharpCodeStyleOptions.PreferNotPattern, syntaxTree, cancellationToken);
if (!styleOption.Value)
return;
// Look for the form: !(x is Y y)
if (!(node is PrefixUnaryExpressionSyntax
{
Operand: ParenthesizedExpressionSyntax
{
Expression: IsPatternExpressionSyntax
{
Pattern: DeclarationPatternSyntax,
} isPattern,
},
} notExpression))
{
return;
}
// Put a diagnostic with the appropriate severity on `is` keyword.
syntaxContext.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
isPattern.IsKeyword.GetLocation(),
styleOption.Notification.Severity,
ImmutableArray.Create(notExpression.GetLocation()),
properties: null));
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaDocumentExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaDocumentExtensions
{
public static Task<SemanticModel> GetSemanticModelForNodeAsync(this Document document, SyntaxNode? node, CancellationToken cancellationToken)
=> DocumentExtensions.ReuseExistingSpeculativeModelAsync(document, node, cancellationToken).AsTask();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaDocumentExtensions
{
public static Task<SemanticModel> GetSemanticModelForNodeAsync(this Document document, SyntaxNode? node, CancellationToken cancellationToken)
=> DocumentExtensions.ReuseExistingSpeculativeModelAsync(document, node, cancellationToken).AsTask();
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/LocalsWindow_InProc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using EnvDTE80;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class LocalsWindow_InProc : InProcComponent
{
public static LocalsWindow_InProc Create() => new LocalsWindow_InProc();
public int GetCount()
{
var dte = ((DTE2)GetDTE());
if (dte.Debugger.CurrentStackFrame != null) // Ensure that debugger is running
{
var locals = dte.Debugger.CurrentStackFrame.Locals;
return locals.Count;
}
return 0;
}
public Common.Expression GetEntry(params string[] entryNames)
{
var dte = ((DTE2)GetDTE());
if (dte.Debugger.CurrentStackFrame == null) // Ensure that debugger is running
{
throw new Exception($"Could not find locals. Debugger is not running.");
}
var expressions = dte.Debugger.CurrentStackFrame.Locals;
EnvDTE.Expression? entry = null;
var i = 0;
while (i < entryNames.Length && TryGetEntryInternal(entryNames[i], expressions, out entry))
{
i++;
expressions = entry.DataMembers;
}
if ((i == entryNames.Length) && (entry != null))
{
return new Common.Expression(entry);
}
var localHierarchicalName = string.Join("->", entryNames);
var allLocalsString = string.Join("\n", GetAllLocals(dte.Debugger.CurrentStackFrame.Locals));
throw new Exception($"\nCould not find the local named {localHierarchicalName}.\nAll available locals are: \n{allLocalsString}");
}
private bool TryGetEntryInternal(string entryName, EnvDTE.Expressions expressions, out EnvDTE.Expression expression)
{
expression = expressions.Cast<EnvDTE.Expression>().FirstOrDefault(e => e.Name == entryName);
if (expression != null)
{
return true;
}
return false;
}
private static IEnumerable<string> GetAllLocals(EnvDTE.Expressions expressions)
{
foreach (var expression in expressions.Cast<EnvDTE.Expression>())
{
var expressionName = expression.Name;
yield return expressionName;
var nestedExpressions = expression.DataMembers;
if (nestedExpressions != null)
{
foreach (var nestedLocal in GetAllLocals(nestedExpressions))
{
yield return string.Format("{0}->{1}", expressionName, nestedLocal);
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using EnvDTE80;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class LocalsWindow_InProc : InProcComponent
{
public static LocalsWindow_InProc Create() => new LocalsWindow_InProc();
public int GetCount()
{
var dte = ((DTE2)GetDTE());
if (dte.Debugger.CurrentStackFrame != null) // Ensure that debugger is running
{
var locals = dte.Debugger.CurrentStackFrame.Locals;
return locals.Count;
}
return 0;
}
public Common.Expression GetEntry(params string[] entryNames)
{
var dte = ((DTE2)GetDTE());
if (dte.Debugger.CurrentStackFrame == null) // Ensure that debugger is running
{
throw new Exception($"Could not find locals. Debugger is not running.");
}
var expressions = dte.Debugger.CurrentStackFrame.Locals;
EnvDTE.Expression? entry = null;
var i = 0;
while (i < entryNames.Length && TryGetEntryInternal(entryNames[i], expressions, out entry))
{
i++;
expressions = entry.DataMembers;
}
if ((i == entryNames.Length) && (entry != null))
{
return new Common.Expression(entry);
}
var localHierarchicalName = string.Join("->", entryNames);
var allLocalsString = string.Join("\n", GetAllLocals(dte.Debugger.CurrentStackFrame.Locals));
throw new Exception($"\nCould not find the local named {localHierarchicalName}.\nAll available locals are: \n{allLocalsString}");
}
private bool TryGetEntryInternal(string entryName, EnvDTE.Expressions expressions, out EnvDTE.Expression expression)
{
expression = expressions.Cast<EnvDTE.Expression>().FirstOrDefault(e => e.Name == entryName);
if (expression != null)
{
return true;
}
return false;
}
private static IEnumerable<string> GetAllLocals(EnvDTE.Expressions expressions)
{
foreach (var expression in expressions.Cast<EnvDTE.Expression>())
{
var expressionName = expression.Name;
yield return expressionName;
var nestedExpressions = expression.DataMembers;
if (nestedExpressions != null)
{
foreach (var nestedLocal in GetAllLocals(nestedExpressions))
{
yield return string.Format("{0}->{1}", expressionName, nestedLocal);
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Extensibility/NavigationBar/INavigationBarControllerFactoryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor
{
internal interface INavigationBarControllerFactoryService
{
IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor
{
internal interface INavigationBarControllerFactoryService
{
IDisposable CreateController(INavigationBarPresenter presenter, ITextBuffer textBuffer);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenDeconstructTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
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.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
[CompilerTrait(CompilerFeature.Tuples)]
public class CodeGenDeconstructTests : CSharpTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
const string commonSource =
@"public class Pair<T1, T2>
{
T1 item1;
T2 item2;
public Pair(T1 item1, T2 item2)
{
this.item1 = item1;
this.item2 = item2;
}
public void Deconstruct(out T1 item1, out T2 item2)
{
System.Console.WriteLine($""Deconstructing {ToString()}"");
item1 = this.item1;
item2 = this.item2;
}
public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; }
}
public static class Pair
{
public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); }
}
public class Integer
{
public int state;
public override string ToString() { return state.ToString(); }
public Integer(int i) { state = i; }
public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); }
}
public class LongInteger
{
long state;
public LongInteger(long l) { state = l; }
public override string ToString() { return state.ToString(); }
}";
[Fact]
public void SimpleAssign()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(x, y)", lhs.ToString());
Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
var right = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal(@"new C()", right.ToString());
Assert.Equal("C", model.GetTypeInfo(right).Type.ToTestDisplayString());
Assert.Equal("C", model.GetTypeInfo(right).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(right).Kind);
};
var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 hello", references: s_valueTupleRefs, sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (long V_0, //x
string V_1, //y
int V_2,
string V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_2
IL_0007: ldloca.s V_3
IL_0009: callvirt ""void C.Deconstruct(out int, out string)""
IL_000e: ldloc.2
IL_000f: conv.i8
IL_0010: stloc.0
IL_0011: ldloc.3
IL_0012: stloc.1
IL_0013: ldloca.s V_0
IL_0015: call ""string long.ToString()""
IL_001a: ldstr "" ""
IL_001f: ldloc.1
IL_0020: call ""string string.Concat(string, string, string)""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
}");
}
[Fact]
public void ObsoleteDeconstructMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
foreach (var (z1, z2) in new[] { new C() }) { }
}
[System.Obsolete]
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,18): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete
// (x, y) = new C();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 18),
// (10,34): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete
// foreach (var (z1, z2) in new[] { new C() }) { }
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new[] { new C() }").WithArguments("C.Deconstruct(out int, out string)").WithLocation(10, 34)
);
}
[Fact]
[WorkItem(13632, "https://github.com/dotnet/roslyn/issues/13632")]
public void SimpleAssignWithoutConversion()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (int V_0, //x
string V_1, //y
int V_2,
string V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_2
IL_0007: ldloca.s V_3
IL_0009: callvirt ""void C.Deconstruct(out int, out string)""
IL_000e: ldloc.2
IL_000f: stloc.0
IL_0010: ldloc.3
IL_0011: stloc.1
IL_0012: ldloca.s V_0
IL_0014: call ""string int.ToString()""
IL_0019: ldstr "" ""
IL_001e: ldloc.1
IL_001f: call ""string string.Concat(string, string, string)""
IL_0024: call ""void System.Console.WriteLine(string)""
IL_0029: ret
}");
}
[Fact]
public void DeconstructMethodAmbiguous()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
public void Deconstruct(out int a)
{
a = 2;
}
}";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree);
var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode();
Assert.Equal("(x, y) = new C()", deconstruction.ToString());
var deconstructionInfo = model.GetDeconstructionInfo(deconstruction);
var firstDeconstructMethod = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C").GetMembers(WellKnownMemberNames.DeconstructMethodName)
.OfType<SourceOrdinaryMethodSymbol>().Where(m => m.ParameterCount == 2).Single();
Assert.Equal(firstDeconstructMethod.GetPublicSymbol(), deconstructionInfo.Method);
Assert.Equal("void C.Deconstruct(out System.Int32 a, out System.String b)",
deconstructionInfo.Method.ToTestDisplayString());
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.ImplicitNumeric, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Null(nested[1].Method);
Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind);
Assert.Empty(nested[1].Nested);
var assignment = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression, occurrence: 2).AsNode();
Assert.Equal("a = 1", assignment.ToString());
var defaultInfo = model.GetDeconstructionInfo(assignment);
Assert.Null(defaultInfo.Method);
Assert.Empty(defaultInfo.Nested);
Assert.Equal(ConversionKind.UnsetConversionKind, defaultInfo.Conversion.Value.Kind);
}
[Fact]
[WorkItem(27520, "https://github.com/dotnet/roslyn/issues/27520")]
public void GetDeconstructionInfoOnIncompleteCode()
{
string source = @"
class C
{
static void M(string s)
{
foreach (char in s) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,18): error CS1525: Invalid expression term 'char'
// foreach (char in s) { }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "char").WithArguments("char").WithLocation(6, 18),
// (6,23): error CS0230: Type and identifier are both required in a foreach statement
// foreach (char in s) { }
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 23)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var foreachDeconstruction = (ForEachVariableStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode();
Assert.Equal(@"foreach (char in s) { }", foreachDeconstruction.ToString());
var deconstructionInfo = model.GetDeconstructionInfo(foreachDeconstruction);
Assert.Equal(Conversion.UnsetConversion, deconstructionInfo.Conversion);
Assert.Null(deconstructionInfo.Method);
Assert.Empty(deconstructionInfo.Nested);
}
[Fact]
[WorkItem(15634, "https://github.com/dotnet/roslyn/issues/15634")]
public void DeconstructMustReturnVoid()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
}
public int Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
return 42;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18)
);
}
[Fact]
public void VerifyExecutionOrder_Deconstruct()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForX().x, c.getHolderForY().y) = c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
getDeconstructReceiver
Deconstruct
Conversion1
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_Deconstruct_Conditional()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
bool b = true;
(c.getHolderForX().x, c.getHolderForY().y) = b ? c.getDeconstructReceiver() : default;
}
public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
getDeconstructReceiver
Deconstruct
Conversion1
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteral()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForX().x, c.getHolderForY().y) = (new D1(), new D2());
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
Constructor1
Conversion1
Constructor2
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteral_Conditional()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
static void Main()
{
C c = new C();
bool b = true;
(c.getHolderForX().x, c.getHolderForY().y) = b ? (new D1(), new D2()) : default;
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
Constructor1
Constructor2
Conversion1
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteralAndDeconstruction()
{
string source = @"
using System;
class C
{
int w { set { Console.WriteLine($""setW""); } }
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = (new D1(), new D2(), new D3());
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); }
}
class D3
{
public D3() { Console.WriteLine(""Constructor3""); }
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforW
getHolderforY
getHolderforZ
getHolderforX
Constructor1
Conversion1
Constructor2
Constructor3
Conversion3
deconstruct
setW
setY
setZ
setX
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteralAndDeconstruction_Conditional()
{
string source = @"
using System;
class C
{
int w { set { Console.WriteLine($""setW""); } }
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
static void Main()
{
C c = new C();
bool b = false;
(c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = b ? default : (new D1(), new D2(), new D3());
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); }
}
class D3
{
public D3() { Console.WriteLine(""Constructor3""); }
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforW
getHolderforY
getHolderforZ
getHolderforX
Constructor1
Constructor2
Constructor3
deconstruct
Conversion1
Conversion3
setW
setY
setZ
setX
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void DifferentVariableKinds()
{
string source = @"
class C
{
int[] ArrayIndexer = new int[1];
string property;
string Property { set { property = value; } }
string AutoProperty { get; set; }
static void Main()
{
C c = new C();
(c.ArrayIndexer[0], c.Property, c.AutoProperty) = new C();
System.Console.WriteLine(c.ArrayIndexer[0] + "" "" + c.property + "" "" + c.AutoProperty);
}
public void Deconstruct(out int a, out string b, out string c)
{
a = 1;
b = ""hello"";
c = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello world");
comp.VerifyDiagnostics();
}
[Fact]
public void Dynamic()
{
string source = @"
class C
{
dynamic Dynamic1;
dynamic Dynamic2;
static void Main()
{
C c = new C();
(c.Dynamic1, c.Dynamic2) = c;
System.Console.WriteLine(c.Dynamic1 + "" "" + c.Dynamic2);
}
public void Deconstruct(out int a, out dynamic b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructInterfaceOnStruct()
{
string source = @"
interface IDeconstructable
{
void Deconstruct(out int a, out string b);
}
struct C : IDeconstructable
{
string state;
static void Main()
{
int x;
string y;
IDeconstructable c = new C() { state = ""initial"" };
System.Console.Write(c);
(x, y) = c;
System.Console.WriteLine("" "" + c + "" "" + x + "" "" + y);
}
void IDeconstructable.Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
state = ""modified"";
}
public override string ToString() { return state; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "initial modified 1 hello", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructMethodHasParams2()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator
{
a = 1;
b = ""ignored"";
}
public void Deconstruct(out int a, out string b)
{
a = 2;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "2 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void OutParamsDisallowed()
{
string source = @"
class C
{
public void Deconstruct(out int a, out string b, out params int[] c)
{
a = 1;
b = ""ignored"";
c = new[] { 2, 2 };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,58): error CS8328: The parameter modifier 'params' cannot be used with 'out'
// public void Deconstruct(out int a, out string b, out params int[] c)
Diagnostic(ErrorCode.ERR_BadParameterModifiers, "params").WithArguments("params", "out").WithLocation(4, 58));
}
[Fact]
public void DeconstructMethodHasArglist2()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator
{
a = 2;
b = ""ignored"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DifferentStaticVariableKinds()
{
string source = @"
class C
{
static int[] ArrayIndexer = new int[1];
static string property;
static string Property { set { property = value; } }
static string AutoProperty { get; set; }
static void Main()
{
(C.ArrayIndexer[0], C.Property, C.AutoProperty) = new C();
System.Console.WriteLine(C.ArrayIndexer[0] + "" "" + C.property + "" "" + C.AutoProperty);
}
public void Deconstruct(out int a, out string b, out string c)
{
a = 1;
b = ""hello"";
c = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello world");
comp.VerifyDiagnostics();
}
[Fact]
public void DifferentVariableRefKinds()
{
string source = @"
class C
{
static void Main()
{
long a = 1;
int b;
C.M(ref a, out b);
System.Console.WriteLine(a + "" "" + b);
}
static void M(ref long a, out int b)
{
(a, b) = new C();
}
public void Deconstruct(out int x, out byte y)
{
x = 2;
y = (byte)3;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "2 3");
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void RefReturningMethod()
{
string source = @"
class C
{
static int i = 0;
static void Main()
{
(M(), M()) = new C();
System.Console.WriteLine($""Final i is {i}"");
}
static ref int M()
{
System.Console.WriteLine($""M (previous i is {i})"");
return ref i;
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 42;
y = 43;
}
}
";
var expected =
@"M (previous i is 0)
M (previous i is 0)
Deconstruct
Final i is 43
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void RefReturningProperty()
{
string source = @"
class C
{
static int i = 0;
static void Main()
{
(P, P) = new C();
System.Console.WriteLine($""Final i is {i}"");
}
static ref int P
{
get
{
System.Console.WriteLine($""P (previous i is {i})"");
return ref i;
}
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 42;
y = 43;
}
}
";
var expected =
@"P (previous i is 0)
P (previous i is 0)
Deconstruct
Final i is 43
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void RefReturningMethodFlow()
{
string source = @"
struct C
{
static C i;
static C P { get { System.Console.WriteLine(""getP""); return i; } set { System.Console.WriteLine(""setP""); i = value; } }
static void Main()
{
(M(), M()) = P;
}
static ref C M()
{
System.Console.WriteLine($""M (previous i is {i})"");
return ref i;
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 42;
y = 43;
}
public static implicit operator C(int x)
{
System.Console.WriteLine(""conversion"");
return new C();
}
}
";
var expected =
@"M (previous i is C)
M (previous i is C)
getP
Deconstruct
conversion
conversion";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void Indexers()
{
string source = @"
class C
{
static SomeArray array;
static void Main()
{
int y;
(Goo()[Bar()], y) = new C();
System.Console.WriteLine($""Final array values[2] {array.values[2]}"");
}
static SomeArray Goo()
{
System.Console.WriteLine($""Goo"");
array = new SomeArray();
return array;
}
static int Bar()
{
System.Console.WriteLine($""Bar"");
return 2;
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 101;
y = 102;
}
}
class SomeArray
{
public int[] values;
public SomeArray() { values = new [] { 42, 43, 44 }; }
public int this[int index] {
get { System.Console.WriteLine($""indexGet (with value {values[index]})""); return values[index]; }
set { System.Console.WriteLine($""indexSet (with value {value})""); values[index] = value; }
}
}
";
var expected =
@"Goo
Bar
Deconstruct
indexSet (with value 101)
Final array values[2] 101
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningTuple()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
int i = 1;
(x, y) = (i, ""hello"");
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree);
var deconstruction = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single();
var deconstructionInfo = model.GetDeconstructionInfo(deconstruction);
Assert.Null(deconstructionInfo.Method);
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Null(nested[1].Method);
Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind);
Assert.Empty(nested[1].Nested);
var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(i, ""hello"")", tuple.ToString());
var tupleConversion = model.GetConversion(tuple);
Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.Kind);
Assert.Equal(ConversionKind.ImplicitNumeric, tupleConversion.UnderlyingConversions[0].Kind);
}
[Fact]
public void AssigningTupleWithConversion()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = M();
System.Console.WriteLine(x + "" "" + y);
}
static System.ValueTuple<int, string> M()
{
return (1, ""hello"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningLongTuple()
{
string source = @"
class C
{
static void Main()
{
long x;
int y;
(x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, 2);
System.Console.WriteLine(string.Concat(x, "" "", y));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "4 2");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0) //y
IL_0000: ldc.i4.4
IL_0001: conv.i8
IL_0002: ldc.i4.2
IL_0003: stloc.0
IL_0004: box ""long""
IL_0009: ldstr "" ""
IL_000e: ldloc.0
IL_000f: box ""int""
IL_0014: call ""string string.Concat(object, object, object)""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: ret
}");
}
[Fact]
public void AssigningLongTupleWithNames()
{
string source = @"
class C
{
static void Main()
{
long x;
int y;
(x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "9 10");
comp.VerifyDiagnostics(
// (9,43): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 43),
// (9,49): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 49),
// (9,55): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 55),
// (9,61): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 61),
// (9,67): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 5").WithArguments("e", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 67),
// (9,73): warning CS8123: The tuple element name 'f' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f: 6").WithArguments("f", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 73),
// (9,79): warning CS8123: The tuple element name 'g' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "g: 7").WithArguments("g", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 79),
// (9,85): warning CS8123: The tuple element name 'h' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "h: 8").WithArguments("h", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 85),
// (9,91): warning CS8123: The tuple element name 'i' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "i: 9").WithArguments("i", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 91),
// (9,97): warning CS8123: The tuple element name 'j' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "j: 10").WithArguments("j", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 97)
);
}
[Fact]
public void AssigningLongTuple2()
{
string source = @"
class C
{
static void Main()
{
long x;
int y;
(x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, (byte)2);
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "4 2");
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningTypelessTuple()
{
string source = @"
class C
{
static void Main()
{
string x = ""goodbye"";
string y;
(x, y) = (null, ""hello"");
System.Console.WriteLine($""{x}{y}"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (string V_0) //y
IL_0000: ldnull
IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""string string.Concat(string, string)""
IL_000d: call ""void System.Console.WriteLine(string)""
IL_0012: ret
} ");
}
[Fact]
public void ValueTupleReturnIsNotEmittedIfUnused()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = new C();
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0,
int V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_0
IL_0007: ldloca.s V_1
IL_0009: callvirt ""void C.Deconstruct(out int, out int)""
IL_000e: ret
}");
}
[Fact]
public void ValueTupleReturnIsEmittedIfUsed()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
var z = ((x, y) = new C());
z.ToString();
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2);
Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString());
};
var comp = CompileAndVerify(source, sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 37 (0x25)
.maxstack 3
.locals init (System.ValueTuple<int, int> V_0, //z
int V_1,
int V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_1
IL_0007: ldloca.s V_2
IL_0009: callvirt ""void C.Deconstruct(out int, out int)""
IL_000e: ldloc.1
IL_000f: ldloc.2
IL_0010: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0015: stloc.0
IL_0016: ldloca.s V_0
IL_0018: constrained. ""System.ValueTuple<int, int>""
IL_001e: callvirt ""string object.ToString()""
IL_0023: pop
IL_0024: ret
}");
}
[Fact]
public void ValueTupleReturnIsEmittedIfUsed_WithCSharp7_1()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
var z = ((x, y) = new C());
z.ToString();
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2);
Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString());
};
var comp = CompileAndVerify(source,
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleNotRequiredIfReturnIsNotUsed()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = new C();
System.Console.Write($""assignment: {x} {y}. "");
foreach (var (a, b) in new[] { new C() })
{
System.Console.Write($""foreach: {a} {b}."");
}
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "assignment: 1 2. foreach: 1 2.");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var xy = nodes.OfType<TupleExpressionSyntax>().Single();
Assert.Equal("(x, y)", xy.ToString());
var tuple1 = model.GetTypeInfo(xy).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tuple1.ToTestDisplayString());
var ab = nodes.OfType<DeclarationExpressionSyntax>().Single();
var tuple2 = model.GetTypeInfo(ab).Type;
Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", tuple2.ToTestDisplayString());
Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", model.GetTypeInfo(ab).ConvertedType.ToTestDisplayString());
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleNotRequiredIfReturnIsNotUsed2()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
for((x, y) = new C(1); ; (x, y) = new C(2))
{
}
}
public C(int c) { }
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var tuple1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0);
Assert.Equal("(x, y) = new C(1)", tuple1.Parent.ToString());
var tupleType1 = model.GetTypeInfo(tuple1).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType1.ToTestDisplayString());
var tuple2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal("(x, y) = new C(2)", tuple2.Parent.ToString());
var tupleType2 = model.GetTypeInfo(tuple1).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType2.ToTestDisplayString());
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleNotRequiredIfReturnIsNotUsed3()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = new C();
}
public C() { }
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
namespace System
{
[Obsolete]
public struct ValueTuple<T1, T2>
{
[Obsolete]
public T1 Item1;
[Obsolete]
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; }
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyEmitDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var tuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0);
Assert.Equal("(x, y) = new C()", tuple.Parent.ToString());
var tupleType = model.GetTypeInfo(tuple).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)", tupleType.ToTestDisplayString());
var underlying = ((INamedTypeSymbol)tupleType).TupleUnderlyingType;
Assert.Equal("(System.Int32, System.Int32)", underlying.ToTestDisplayString());
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleRequiredWhenRightHandSideIsTuple()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = (1, 2);
}
}
";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics(
// (7,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(7, 18)
);
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleRequiredWhenRightHandSideIsTupleButNoReferenceEmitted()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
Action<PEAssembly> assemblyValidator = assembly =>
{
var reader = assembly.GetMetadataReader();
var names = reader.GetAssemblyRefNames().Select(name => reader.GetString(name));
Assert.Empty(names.Where(name => name.Contains("ValueTuple")));
};
CompileAndVerifyCommon(comp, assemblyValidator: assemblyValidator);
}
[Fact]
public void ValueTupleReturnMissingMemberWithCSharp7()
{
string source = @"
class C
{
public void M()
{
int x, y;
var nested = ((x, y) = (1, 2));
System.Console.Write(nested.x);
}
}
";
var comp = CreateCompilation(source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyDiagnostics(
// (8,37): error CS8305: Tuple element name 'x' is inferred. Please use language version 7.1 or greater to access an element by its inferred name.
// System.Console.Write(nested.x);
Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "x").WithArguments("x", "7.1").WithLocation(8, 37)
);
}
[Fact]
public void ValueTupleReturnWithInferredNamesWithCSharp7_1()
{
string source = @"
class C
{
public void M()
{
int x, y, Item1, Rest;
var a = ((x, y) = (1, 2));
var b = ((x, x) = (1, 2));
var c = ((_, x) = (1, 2));
var d = ((Item1, Rest) = (1, 2));
var nested = ((x, Item1, y, (_, x, x), (x, y)) = (1, 2, 3, (4, 5, 6), (7, 8)));
(int, int) f = ((x, y) = (1, 2));
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var declarations = nodes.OfType<VariableDeclaratorSyntax>();
Assert.Equal("(System.Int32 x, System.Int32 y) a", model.GetDeclaredSymbol(declarations.ElementAt(4)).ToTestDisplayString());
Assert.Equal("(System.Int32, System.Int32) b", model.GetDeclaredSymbol(declarations.ElementAt(5)).ToTestDisplayString());
Assert.Equal("(System.Int32, System.Int32 x) c", model.GetDeclaredSymbol(declarations.ElementAt(6)).ToTestDisplayString());
var x = (ILocalSymbol)model.GetDeclaredSymbol(declarations.ElementAt(7));
Assert.Equal("(System.Int32, System.Int32) d", x.ToTestDisplayString());
Assert.True(x.Type.GetSymbol().TupleElementNames.IsDefault);
Assert.Equal("(System.Int32 x, System.Int32, System.Int32 y, (System.Int32, System.Int32, System.Int32), (System.Int32 x, System.Int32 y)) nested",
model.GetDeclaredSymbol(declarations.ElementAt(8)).ToTestDisplayString());
};
var comp = CompileAndVerify(source,
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionDeclarationCanOnlyBeParsedAsStatement()
{
string source = @"
class C
{
public static void Main()
{
var z = ((var x, int y) = new C());
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,19): error CS8185: A declaration is not allowed in this context.
// var z = ((var x, int y) = new C());
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x").WithLocation(6, 19)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void Constraints_01()
{
string source = @"
using System;
class C
{
public void M()
{
(int x, var (err1, y)) = (0, new C()); // ok, no return value used
(ArgIterator err2, var err3) = M2(); // ok, no return value
foreach ((ArgIterator err4, var err5) in new[] { M2() }) // ok, no return value
{
}
}
public static (ArgIterator, ArgIterator) M2()
{
return (default(ArgIterator), default(ArgIterator));
}
public void Deconstruct(out ArgIterator a, out int b)
{
a = default(ArgIterator);
b = 2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (19,29): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// public void Deconstruct(out ArgIterator a, out int b)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator a").WithArguments("System.ArgIterator").WithLocation(19, 29),
// (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument
// public static (ArgIterator, ArgIterator) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46),
// (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument
// public static (ArgIterator, ArgIterator) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46),
// (16,17): error CS0306: The type 'ArgIterator' may not be used as a type argument
// return (default(ArgIterator), default(ArgIterator));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 17),
// (16,39): error CS0306: The type 'ArgIterator' may not be used as a type argument
// return (default(ArgIterator), default(ArgIterator));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 39)
);
}
[Fact]
public void Constraints_02()
{
string source = @"
unsafe class C
{
public void M()
{
(int x, var (err1, y)) = (0, new C()); // ok, no return value
(var err2, var err3) = M2(); // ok, no return value
foreach ((var err4, var err5) in new[] { M2() }) // ok, no return value
{
}
}
public static (int*, int*) M2()
{
return (default(int*), default(int*));
}
public void Deconstruct(out int* a, out int b)
{
a = default(int*);
b = 2;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (13,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32),
// (13,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32),
// (15,17): error CS0306: The type 'int*' may not be used as a type argument
// return (default(int*), default(int*));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 17),
// (15,32): error CS0306: The type 'int*' may not be used as a type argument
// return (default(int*), default(int*));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 32)
);
}
[Fact]
public void Constraints_03()
{
string source = @"
unsafe class C
{
public void M()
{
int ok;
int* err1, err2;
var t = ((ok, (err1, ok)) = (0, new C()));
var t2 = ((err1, err2) = M2());
}
public static (int*, int*) M2()
{
throw null;
}
public void Deconstruct(out int* a, out int b)
{
a = default(int*);
b = 2;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (12,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32),
// (12,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32),
// (8,24): error CS0306: The type 'int*' may not be used as a type argument
// var t = ((ok, (err1, ok)) = (0, new C()));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(8, 24),
// (9,20): error CS0306: The type 'int*' may not be used as a type argument
// var t2 = ((err1, err2) = M2());
Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(9, 20),
// (9,26): error CS0306: The type 'int*' may not be used as a type argument
// var t2 = ((err1, err2) = M2());
Diagnostic(ErrorCode.ERR_BadTypeArgument, "err2").WithArguments("int*").WithLocation(9, 26)
);
}
[Fact]
public void DeconstructionWithTupleNamesCannotBeParsed()
{
string source = @"
class C
{
public static void Main()
{
(Alice: var x, Bob: int y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,10): error CS8187: Tuple element names are not permitted on the left of a deconstruction.
// (Alice: var x, Bob: int y) = (1, 2);
Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Alice:").WithLocation(6, 10),
// (6,24): error CS8187: Tuple element names are not permitted on the left of a deconstruction.
// (Alice: var x, Bob: int y) = (1, 2);
Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Bob:").WithLocation(6, 24)
);
}
[Fact]
public void ValueTupleReturnIsEmittedIfUsedInLambda()
{
string source = @"
class C
{
static void F(System.Action a) { }
static void F<T>(System.Func<T> f) { System.Console.Write(f().ToString()); }
static void Main()
{
int x, y;
F(() => (x, y) = (1, 2));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 2)");
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningIntoProperties()
{
string source = @"
class C
{
static int field;
static long x { set { System.Console.WriteLine($""setX {value}""); } }
static string y { get; set; }
static ref int z { get { return ref field; } }
static void Main()
{
(x, y, z) = new C();
System.Console.WriteLine(y);
System.Console.WriteLine($""field: {field}"");
}
public void Deconstruct(out int a, out string b, out int c)
{
a = 1;
b = ""hello"";
c = 2;
}
}
";
string expected =
@"setX 1
hello
field: 2
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningTupleIntoProperties()
{
string source = @"
class C
{
static int field;
static long x { set { System.Console.WriteLine($""setX {value}""); } }
static string y { get; set; }
static ref int z { get { return ref field; } }
static void Main()
{
(x, y, z) = (1, ""hello"", 2);
System.Console.WriteLine(y);
System.Console.WriteLine($""field: {field}"");
}
}
";
string expected =
@"setX 1
hello
field: 2
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")]
public void AssigningIntoIndexers()
{
string source = @"
using System;
class C
{
int field;
ref int this[int x, int y, int z, int opt = 1]
{
get
{
Console.WriteLine($""this.get"");
return ref field;
}
}
int this[int x, long y, int z, int opt = 1]
{
set
{
Console.WriteLine($""this.set({value})"");
}
}
int M(int i)
{
Console.WriteLine($""M({i})"");
return 0;
}
void Test()
{
(this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = this;
Console.WriteLine($""field: {field}"");
}
static void Main()
{
new C().Test();
}
void Deconstruct(out int a, out int b)
{
Console.WriteLine(nameof(Deconstruct));
a = 1;
b = 2;
}
}
";
var expectedOutput =
@"M(1)
M(2)
this.get
M(3)
M(4)
Deconstruct
this.set(2)
field: 1
";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")]
public void AssigningTupleIntoIndexers()
{
string source = @"
using System;
class C
{
int field;
ref int this[int x, int y, int z, int opt = 1]
{
get
{
Console.WriteLine($""this.get"");
return ref field;
}
}
int this[int x, long y, int z, int opt = 1]
{
set
{
Console.WriteLine($""this.set({value})"");
}
}
int M(int i)
{
Console.WriteLine($""M({i})"");
return 0;
}
void Test()
{
(this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = (1, 2);
Console.WriteLine($""field: {field}"");
}
static void Main()
{
new C().Test();
}
}
";
var expectedOutput =
@"M(1)
M(2)
this.get
M(3)
M(4)
this.set(2)
field: 1
";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningIntoIndexerWithOptionalValueParameter()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
01 00 04 49 74 65 6d 00 00
)
.method public hidebysig specialname
instance void set_Item (
int32 i,
[opt] int32 'value'
) cil managed
{
.param [2] = int32(1)
.maxstack 8
IL_0000: ldstr ""this.set({0})""
IL_0005: ldarg.2
IL_0006: box[mscorlib]System.Int32
IL_000b: call string[mscorlib] System.String::Format(string, object)
IL_0010: call void [mscorlib]System.Console::WriteLine(string)
IL_0015: ret
} // end of method C::set_Item
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
.property instance int32 Item(
int32 i
)
{
.set instance void C::set_Item(int32, int32)
}
} // end of class C
";
var source = @"
class Program
{
static void Main()
{
var c = new C();
(c[1], c[2]) = (1, 2);
}
}
";
string expectedOutput =
@"this.set(1)
this.set(2)
";
var comp = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: expectedOutput).VerifyDiagnostics();
}
[Fact]
public void Swap()
{
string source = @"
class C
{
static int x = 2;
static int y = 4;
static void Main()
{
Swap();
System.Console.WriteLine(x + "" "" + y);
}
static void Swap()
{
(x, y) = (y, x);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "4 2");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Swap", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int V_0)
IL_0000: ldsfld ""int C.y""
IL_0005: ldsfld ""int C.x""
IL_000a: stloc.0
IL_000b: stsfld ""int C.x""
IL_0010: ldloc.0
IL_0011: stsfld ""int C.y""
IL_0016: ret
}
");
}
[Fact]
public void CircularFlow()
{
string source = @"
class C
{
static void Main()
{
(object i, object ii) x = (1, 2);
object y;
(x.ii, y) = x;
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2");
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void CircularFlow2()
{
string source = @"
class C
{
static void Main()
{
(object i, object ii) x = (1,2);
object y;
ref var a = ref x;
(a.ii, y) = x;
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructUsingBaseDeconstructMethod()
{
string source = @"
class Base
{
public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
}
class C : Base
{
static void Main()
{
int x, y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int c) { c = 42; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
[Fact]
public void NestedDeconstructUsingSystemTupleExtensionMethod()
{
string source = @"
using System;
class C
{
static void Main()
{
int x;
string y, z;
(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""));
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello world", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree);
var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode();
Assert.Equal(@"(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""))", deconstruction.ToString());
var deconstructionInfo = model.GetDeconstructionInfo(deconstruction);
Assert.Equal("void System.TupleExtensions.Deconstruct<System.Int32, System.Tuple<System.String, System.String>>(" +
"this System.Tuple<System.Int32, System.Tuple<System.String, System.String>> value, " +
"out System.Int32 item1, out System.Tuple<System.String, System.String> item2)",
deconstructionInfo.Method.ToTestDisplayString());
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Equal("void System.TupleExtensions.Deconstruct<System.String, System.String>(" +
"this System.Tuple<System.String, System.String> value, " +
"out System.String item1, out System.String item2)",
nested[1].Method.ToTestDisplayString());
Assert.Null(nested[1].Conversion);
var nested2 = nested[1].Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested2[0].Method);
Assert.Equal(ConversionKind.Identity, nested2[0].Conversion.Value.Kind);
Assert.Empty(nested2[0].Nested);
Assert.Null(nested2[1].Method);
Assert.Equal(ConversionKind.Identity, nested2[1].Conversion.Value.Kind);
Assert.Empty(nested2[1].Nested);
}
[Fact]
public void DeconstructUsingValueTupleExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
int x;
string y, z;
(x, y, z) = (1, 2);
}
}
public static class Extensions
{
public static void Deconstruct(this (int, int) self, out int x, out string y, out string z)
{
throw null;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,25): error CS0029: Cannot implicitly convert type 'int' to 'string'
// (x, y, z) = (1, 2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(8, 25),
// (8,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// (x, y, z) = (1, 2);
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = (1, 2)").WithArguments("2", "3").WithLocation(8, 9)
);
}
[Fact]
public void OverrideDeconstruct()
{
string source = @"
class Base
{
public virtual void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
class C : Base
{
static void Main()
{
int x;
string y;
(x, y) = new C();
}
public override void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; System.Console.WriteLine(""override""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "override", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructRefTuple()
{
string template = @"
using System;
class C
{
static void Main()
{
int VARIABLES; // int x1, x2, ...
(VARIABLES) = (TUPLE).ToTuple(); // (x1, x2, ...) = (1, 2, ...).ToTuple();
System.Console.WriteLine(OUTPUT);
}
}
";
for (int i = 2; i <= 21; i++)
{
var tuple = String.Join(", ", Enumerable.Range(1, i).Select(n => n.ToString()));
var variables = String.Join(", ", Enumerable.Range(1, i).Select(n => $"x{n}"));
var output = String.Join(@" + "" "" + ", Enumerable.Range(1, i).Select(n => $"x{n}"));
var expected = String.Join(" ", Enumerable.Range(1, i).Select(n => n));
var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple).Replace("OUTPUT", output);
var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
}
[Fact]
public void DeconstructExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
}
static class D
{
public static void Deconstruct(this C value, out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructRefExtensionMethod()
{
// https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-01-24.md
string source = @"
struct C
{
static void Main()
{
long x;
string y;
var c = new C();
(x, y) = c;
System.Console.WriteLine(x + "" "" + y);
}
}
static class D
{
public static void Deconstruct(this ref C value, out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (10,9): error CS1510: A ref or out value must be an assignable variable
// (x, y) = c;
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x, y) = c").WithLocation(10, 9)
);
}
[Fact]
public void DeconstructInExtensionMethod()
{
string source = @"
struct C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
}
static class D
{
public static void Deconstruct(this in C value, out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void UnderspecifiedDeconstructGenericExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
}
}
static class Extension
{
public static void Deconstruct<T>(this C value, out int a, out T b)
{
a = 2;
b = default(T);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,18): error CS0411: The type arguments for method 'Extension.Deconstruct<T>(C, out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("Extension.Deconstruct<T>(C, out int, out T)").WithLocation(8, 18),
// (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18)
);
}
[Fact]
public void UnspecifiedGenericMethodIsNotCandidate()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
}
}
static class Extension
{
public static void Deconstruct<T>(this C value, out int a, out T b)
{
a = 2;
b = default(T);
}
public static void Deconstruct(this C value, out int a, out string b)
{
a = 2;
b = ""hello"";
System.Console.Write(""Deconstructed"");
}
}";
var comp = CompileAndVerify(source, expectedOutput: "Deconstructed");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructGenericExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C1<string>();
}
}
public class C1<T> { }
static class Extension
{
public static void Deconstruct<T>(this C1<T> value, out int a, out T b)
{
a = 2;
b = default(T);
System.Console.WriteLine(""Deconstructed"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "Deconstructed");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructGenericMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C1();
}
}
class C1
{
public void Deconstruct<T>(out int a, out T b)
{
a = 2;
b = default(T);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,18): error CS0411: The type arguments for method 'C1.Deconstruct<T>(out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// (x, y) = new C1();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C1()").WithArguments("C1.Deconstruct<T>(out int, out T)").WithLocation(9, 18),
// (9,18): error CS8129: No Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type.
// (x, y) = new C1();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 18)
);
}
[Fact]
public void AmbiguousDeconstructGenericMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C1();
System.Console.Write($""{x} {y}"");
}
}
class C1
{
public void Deconstruct<T>(out int a, out T b)
{
a = 2;
b = default(T);
}
public void Deconstruct(out int a, out string b)
{
a = 2;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "2 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedTupleAssignment()
{
string source = @"
class C
{
static void Main()
{
long x;
string y, z;
(x, (y, z)) = ((int)1, (""a"", ""b""));
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(x, (y, z))", lhs.ToString());
Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "1 a b", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedTypelessTupleAssignment()
{
string source = @"
class C
{
static void Main()
{
string x, y, z;
(x, (y, z)) = (null, (null, null));
System.Console.WriteLine(""nothing"" + x + y + z);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "nothing");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedDeconstructAssignment()
{
string source = @"
class C
{
static void Main()
{
int x;
string y, z;
(x, (y, z)) = new D1();
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
class D1
{
public void Deconstruct(out int item1, out D2 item2)
{
item1 = 1;
item2 = new D2();
}
}
class D2
{
public void Deconstruct(out string item1, out string item2)
{
item1 = ""a"";
item2 = ""b"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 a b");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedMixedAssignment1()
{
string source = @"
class C
{
static void Main()
{
int x, y, z;
(x, (y, z)) = (1, new D1());
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
class D1
{
public void Deconstruct(out int item1, out int item2)
{
item1 = 2;
item2 = 3;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedMixedAssignment2()
{
string source = @"
class C
{
static void Main()
{
int x;
string y, z;
(x, (y, z)) = new D1();
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
class D1
{
public void Deconstruct(out int item1, out (string, string) item2)
{
item1 = 1;
item2 = (""a"", ""b"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 a b");
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyNestedExecutionOrder()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); }
}
class C1
{
public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
class D3
{
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforX
getHolderforY
getHolderforZ
getDeconstructReceiver
Deconstruct1
Deconstruct2
Conversion1
Conversion2
Conversion3
setX
setY
setZ
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyNestedExecutionOrder_Conditional()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
bool b = false;
(c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); }
}
class C1
{
public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
class D3
{
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforX
getHolderforY
getHolderforZ
getDeconstructReceiver
Deconstruct1
Deconstruct2
Conversion1
Conversion2
Conversion3
setX
setY
setZ
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyNestedExecutionOrder2()
{
string source = @"
using System;
class C
{
static LongInteger x1 { set { Console.WriteLine($""setX1 {value}""); } }
static LongInteger x2 { set { Console.WriteLine($""setX2 {value}""); } }
static LongInteger x3 { set { Console.WriteLine($""setX3 {value}""); } }
static LongInteger x4 { set { Console.WriteLine($""setX4 {value}""); } }
static LongInteger x5 { set { Console.WriteLine($""setX5 {value}""); } }
static LongInteger x6 { set { Console.WriteLine($""setX6 {value}""); } }
static LongInteger x7 { set { Console.WriteLine($""setX7 {value}""); } }
static void Main()
{
((x1, (x2, x3)), ((x4, x5), (x6, x7))) = Pair.Create(Pair.Create(new Integer(1), Pair.Create(new Integer(2), new Integer(3))),
Pair.Create(Pair.Create(new Integer(4), new Integer(5)), Pair.Create(new Integer(6), new Integer(7))));
}
}
" + commonSource;
string expected =
@"Deconstructing ((1, (2, 3)), ((4, 5), (6, 7)))
Deconstructing (1, (2, 3))
Deconstructing (2, 3)
Deconstructing ((4, 5), (6, 7))
Deconstructing (4, 5)
Deconstructing (6, 7)
Converting 1
Converting 2
Converting 3
Converting 4
Converting 5
Converting 6
Converting 7
setX1 1
setX2 2
setX3 3
setX4 4
setX5 5
setX6 6
setX7 7";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void MixOfAssignments()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
C a, b, c;
c = new C();
(x, y) = a = b = c;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/12400")]
[WorkItem(12400, "https://github.com/dotnet/roslyn/issues/12400")]
public void AssignWithPostfixOperator()
{
string source = @"
class C
{
int state = 1;
static void Main()
{
long x;
string y;
C c = new C();
(x, y) = c++;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = state;
b = ""hello"";
}
public static C operator ++(C c1)
{
return new C() { state = 2 };
}
}
";
// https://github.com/dotnet/roslyn/issues/12400
// we expect "2 hello" instead, which means the evaluation order is wrong
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(13631, "https://github.com/dotnet/roslyn/issues/13631")]
public void DeconstructionDeclaration()
{
string source = @"
class C
{
static void Main()
{
var (x1, x2) = (1, ""hello"");
System.Console.WriteLine(x1 + "" "" + x2);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (int V_0, //x1
string V_1) //x2
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldstr ""hello""
IL_0007: stloc.1
IL_0008: ldloca.s V_0
IL_000a: call ""string int.ToString()""
IL_000f: ldstr "" ""
IL_0014: ldloc.1
IL_0015: call ""string string.Concat(string, string, string)""
IL_001a: call ""void System.Console.WriteLine(string)""
IL_001f: ret
}");
}
[Fact]
public void NestedVarDeconstructionDeclaration()
{
string source = @"
class C
{
static void Main()
{
var (x1, (x2, x3)) = (1, (2, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().First();
Assert.Equal(@"var (x1, (x2, x3))", lhs.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var lhsNested = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1);
Assert.Equal(@"(x2, x3)", lhsNested.ToString());
Assert.Null(model.GetTypeInfo(lhsNested).Type);
Assert.Null(model.GetSymbolInfo(lhsNested).Symbol);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionDeclaration_WithCSharp7_1()
{
string source = @"
class C
{
static void Main()
{
(int x1, var (x2, (x3, x4)), var x5) = (1, (2, (3, ""hello"")), 5);
System.Console.WriteLine($""{x1} {x2} {x3} {x4} {x5}"");
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(int x1, var (x2, (x3, x4)), var x5)", lhs.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, (System.Int32 x3, System.String x4)), System.Int32 x5)",
model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var x234 = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1);
Assert.Equal(@"var (x2, (x3, x4))", x234.ToString());
Assert.Equal("(System.Int32 x2, (System.Int32 x3, System.String x4))", model.GetTypeInfo(x234).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x234).Symbol);
var x34 = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1);
Assert.Equal(@"(x3, x4)", x34.ToString());
Assert.Null(model.GetTypeInfo(x34).Type);
Assert.Null(model.GetSymbolInfo(x34).Symbol);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
var x4 = GetDeconstructionVariable(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForDeconstructionLocal(model, x4, x4Ref);
var x5 = GetDeconstructionVariable(tree, "x5");
var x5Ref = GetReference(tree, "x5");
VerifyModelForDeconstructionLocal(model, x5, x5Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 hello 5",
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionAssignment_WithCSharp7_1()
{
string source = @"
class C
{
static void Main()
{
int x1, x2, x3;
(x1, (x2, x3)) = (1, (2, 3));
System.Console.WriteLine($""{x1} {x2} {x3}"");
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x123 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(x1, (x2, x3))", x123.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.Int32 x3))",
model.GetTypeInfo(x123).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x123).Symbol);
var x23 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(x2, x3)", x23.ToString());
Assert.Equal("(System.Int32 x2, System.Int32 x3)", model.GetTypeInfo(x23).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x23).Symbol);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3",
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionDeclaration2()
{
string source = @"
class C
{
static void Main()
{
(var x1, var (x2, x3)) = (1, (2, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal("(var x1, var (x2, x3))", lhs.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1);
Assert.Equal("var (x2, x3)", lhsNested.ToString());
Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhsNested).Symbol);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionDeclarationWithCSharp7_1()
{
string source = @"
class C
{
static void Main()
{
(var x1, byte _, var (x2, x3)) = (1, 2, (3, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal("(var x1, byte _, var (x2, x3))", lhs.ToString());
Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(2);
Assert.Equal("var (x2, x3)", lhsNested.ToString());
Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhsNested).Symbol);
};
var comp = CompileAndVerify(source, sourceSymbolValidator: validator,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyDiagnostics();
}
[Fact]
public void NestedDeconstructionDeclaration()
{
string source = @"
class C
{
static void Main()
{
(int x1, (int x2, string x3)) = (1, (2, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void VarMethodExists()
{
string source = @"
class C
{
static void Main()
{
int x1 = 1;
int x2 = 1;
var (x1, x2);
}
static void var(int a, int b) { System.Console.WriteLine(""var""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "var");
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess1()
{
string source = @"
class C
{
static void Main()
{
(var (x1, x2), string x3) = ((1, 2), null);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: " 1 2");
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess2()
{
string source = @"
class C
{
static void Main()
{
(string x1, byte x2, var x3) = (null, 2, 3);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(string x1, byte x2, var x3)", lhs.ToString());
Assert.Equal("(System.String x1, System.Byte x2, System.Int32 x3)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(null, 2, 3)", literal.ToString());
Assert.Null(model.GetTypeInfo(literal).Type);
Assert.Equal("(System.String, System.Byte, System.Int32)", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind);
};
var comp = CompileAndVerify(source, expectedOutput: " 2 3", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess3()
{
string source = @"
class C
{
static void Main()
{
(string x1, var x2) = (null, (1, 2));
System.Console.WriteLine(x1 + "" "" + x2);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(string x1, var x2)", lhs.ToString());
Assert.Equal("(System.String x1, (System.Int32, System.Int32) x2)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(null, (1, 2))", literal.ToString());
Assert.Null(model.GetTypeInfo(literal).Type);
Assert.Equal("(System.String, (System.Int32, System.Int32))", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind);
var nestedLiteral = literal.Arguments[1].Expression;
Assert.Equal(@"(1, 2)", nestedLiteral.ToString());
Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).Type.ToTestDisplayString());
Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(nestedLiteral).Kind);
};
var comp = CompileAndVerify(source, expectedOutput: " (1, 2)", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess4()
{
string source = @"
class C
{
static void Main()
{
((string x1, byte x2, var x3), int x4) = (M(), 4);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4);
}
static (string, byte, int) M() { return (null, 2, 3); }
}
";
var comp = CompileAndVerify(source, expectedOutput: " 2 3 4");
comp.VerifyDiagnostics();
}
[Fact]
public void VarVarDeclaration()
{
string source = @"
class C
{
static void Main()
{
(var (x1, x2), var x3) = Pair.Create(Pair.Create(1, ""hello""), 2);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
" + commonSource;
string expected =
@"Deconstructing ((1, hello), 2)
Deconstructing (1, hello)
1 hello 2";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular,
sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
private static void VerifyModelForDeconstructionLocal(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.DeconstructionVariable, references);
}
private static void VerifyModelForLocal(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references)
{
VerifyModelForDeconstruction(model, decl, kind, references);
}
private static void VerifyModelForDeconstructionForeach(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.ForEachIterationVariable, references);
}
private static void VerifyModelForDeconstruction(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references)
{
var symbol = model.GetDeclaredSymbol(decl);
Assert.Equal(decl.Identifier.ValueText, symbol.Name);
Assert.Equal(kind, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl));
Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText));
var local = symbol.GetSymbol<SourceLocalSymbol>();
var typeSyntax = GetTypeSyntax(decl);
if (local.IsVar && local.Type.IsErrorType())
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
if (typeSyntax != null)
{
Assert.Equal(local.Type.GetPublicSymbol(), model.GetSymbolInfo(typeSyntax).Symbol);
}
}
foreach (var reference in references)
{
Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText));
Assert.Equal(local.Type.GetPublicSymbol(), model.GetTypeInfo(reference).Type);
}
}
private static void VerifyModelForDeconstructionField(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references)
{
var field = (IFieldSymbol)model.GetDeclaredSymbol(decl);
Assert.Equal(decl.Identifier.ValueText, field.Name);
Assert.Equal(SymbolKind.Field, field.Kind);
Assert.Same(field, model.GetDeclaredSymbol((SyntaxNode)decl));
Assert.Same(field, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.Equal(Accessibility.Private, field.DeclaredAccessibility);
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText));
foreach (var reference in references)
{
Assert.Same(field, model.GetSymbolInfo(reference).Symbol);
Assert.Same(field, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText));
Assert.Equal(field.Type, model.GetTypeInfo(reference).Type);
}
}
private static TypeSyntax GetTypeSyntax(SingleVariableDesignationSyntax decl)
{
return (decl.Parent as DeclarationExpressionSyntax)?.Type;
}
private static SingleVariableDesignationSyntax GetDeconstructionVariable(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single();
}
private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>();
}
private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken);
}
private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name)
{
return GetReferences(tree, name).Single();
}
private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count)
{
var nameRef = GetReferences(tree, name).ToArray();
Assert.Equal(count, nameRef.Length);
return nameRef;
}
private static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name);
}
[Fact]
public void DeclarationWithActualVarType()
{
string source = @"
class C
{
static void Main()
{
(var x1, int x2) = (new var(), 2);
System.Console.WriteLine(x1 + "" "" + x2);
}
}
class var
{
public override string ToString() { return ""var""; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void DeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
(var x1, var x2) = (1, 2);
var (x3, x4) = (3, 4);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
var x4 = GetDeconstructionVariable(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForDeconstructionLocal(model, x4, x4Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x1Type));
var x34Var = (DeclarationExpressionSyntax)x3.Parent.Parent;
Assert.Equal("var", x34Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x34Var.Type).Symbol); // The var in `var (x3, x4)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void DeclarationWithAliasedVarType()
{
string source = @"
using var = D;
class C
{
static void Main()
{
(var x1, int x2) = (new var(), 2);
System.Console.WriteLine(x1 + "" "" + x2);
}
}
class D
{
public override string ToString() { return ""var""; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("D", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
var x1Alias = model.GetAliasInfo(x1Type);
Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind);
Assert.Equal("D", x1Alias.Target.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x2Type));
};
var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
for (var (x1, x2) = (1, 2); x1 < 2; (x1, x2) = (x1 + 1, x2 + 1))
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 4);
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReferences(tree, "x2", 3);
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForWithVarDeconstructInitializersCanParse()
{
string source = @"
using System;
class C
{
static void Main()
{
int x3;
for (var (x1, x2) = (1, 2), x3 = 3; true; )
{
Console.WriteLine(x1);
Console.WriteLine(x2);
Console.WriteLine(x3);
break;
}
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
};
var comp = CompileAndVerify(source, expectedOutput: @"1
2
3", sourceSymbolValidator: validator);
comp.VerifyDiagnostics(
// this is permitted now, as it is just an assignment expression
);
}
[Fact]
public void ForWithActualVarType()
{
string source = @"
class C
{
static void Main()
{
for ((int x1, var x2) = (1, new var()); x1 < 2; x1++)
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
class var
{
public override string ToString() { return ""var""; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 3);
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "1 var", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForWithTypes()
{
string source = @"
class C
{
static void Main()
{
for ((int x1, var x2) = (1, 2); x1 < 2; x1++)
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 3);
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachIEnumerableDeclarationWithImplicitVarType()
{
string source = @"
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
Print(x1, x2);
}
}
static IEnumerable<(int, int)> M() { yield return (1, 2); }
static void Print(object a, object b) { System.Console.WriteLine(a + "" "" + b); }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Equal("(System.Int32 x1, System.Int32 x2)", model.GetTypeInfo(x12Var).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
// verify deconstruction info
var deconstructionForeach = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single();
var deconstructionInfo = model.GetDeconstructionInfo(deconstructionForeach);
Assert.Null(deconstructionInfo.Method);
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Null(nested[1].Method);
Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind);
Assert.Empty(nested[1].Nested);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
var comp7_1 = CompileAndVerify(source, expectedOutput: "1 2",
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp7_1.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> V_0,
int V_1, //x1
int V_2) //x2
IL_0000: call ""System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>> C.M()""
IL_0005: callvirt ""System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>>.GetEnumerator()""
IL_000a: stloc.0
.try
{
IL_000b: br.s IL_0031
IL_000d: ldloc.0
IL_000e: callvirt ""System.ValueTuple<int, int> System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>>.Current.get""
IL_0013: dup
IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0019: stloc.1
IL_001a: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: box ""int""
IL_0026: ldloc.2
IL_0027: box ""int""
IL_002c: call ""void C.Print(object, object)""
IL_0031: ldloc.0
IL_0032: callvirt ""bool System.Collections.IEnumerator.MoveNext()""
IL_0037: brtrue.s IL_000d
IL_0039: leave.s IL_0045
}
finally
{
IL_003b: ldloc.0
IL_003c: brfalse.s IL_0044
IL_003e: ldloc.0
IL_003f: callvirt ""void System.IDisposable.Dispose()""
IL_0044: endfinally
}
IL_0045: ret
}");
}
[Fact]
public void ForEachSZArrayDeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" - "");
}
}
static (int, int)[] M() { return new[] { (1, 2), (3, 4) }; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
var symbol = model.GetDeclaredSymbol(x1);
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 75 (0x4b)
.maxstack 4
.locals init (System.ValueTuple<int, int>[] V_0,
int V_1,
int V_2, //x1
int V_3) //x2
IL_0000: call ""System.ValueTuple<int, int>[] C.M()""
IL_0005: stloc.0
IL_0006: ldc.i4.0
IL_0007: stloc.1
IL_0008: br.s IL_0044
IL_000a: ldloc.0
IL_000b: ldloc.1
IL_000c: ldelem ""System.ValueTuple<int, int>""
IL_0011: dup
IL_0012: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0017: stloc.2
IL_0018: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_001d: stloc.3
IL_001e: ldloca.s V_2
IL_0020: call ""string int.ToString()""
IL_0025: ldstr "" ""
IL_002a: ldloca.s V_3
IL_002c: call ""string int.ToString()""
IL_0031: ldstr "" - ""
IL_0036: call ""string string.Concat(string, string, string, string)""
IL_003b: call ""void System.Console.Write(string)""
IL_0040: ldloc.1
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.1
IL_0044: ldloc.1
IL_0045: ldloc.0
IL_0046: ldlen
IL_0047: conv.i4
IL_0048: blt.s IL_000a
IL_004a: ret
}");
}
[Fact]
public void ForEachMDArrayDeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
Print(x1, x2);
}
}
static (int, int)[,] M() { return new (int, int)[2, 2] { { (1, 2), (3, 4) }, { (5, 6), (7, 8) } }; }
static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 - 5 6 - 7 8 -", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 106 (0x6a)
.maxstack 3
.locals init (System.ValueTuple<int, int>[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4,
int V_5, //x1
int V_6) //x2
IL_0000: call ""System.ValueTuple<int, int>[,] C.M()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.0
IL_0008: callvirt ""int System.Array.GetUpperBound(int)""
IL_000d: stloc.1
IL_000e: ldloc.0
IL_000f: ldc.i4.1
IL_0010: callvirt ""int System.Array.GetUpperBound(int)""
IL_0015: stloc.2
IL_0016: ldloc.0
IL_0017: ldc.i4.0
IL_0018: callvirt ""int System.Array.GetLowerBound(int)""
IL_001d: stloc.3
IL_001e: br.s IL_0065
IL_0020: ldloc.0
IL_0021: ldc.i4.1
IL_0022: callvirt ""int System.Array.GetLowerBound(int)""
IL_0027: stloc.s V_4
IL_0029: br.s IL_005c
IL_002b: ldloc.0
IL_002c: ldloc.3
IL_002d: ldloc.s V_4
IL_002f: call ""(int, int)[*,*].Get""
IL_0034: dup
IL_0035: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_003a: stloc.s V_5
IL_003c: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0041: stloc.s V_6
IL_0043: ldloc.s V_5
IL_0045: box ""int""
IL_004a: ldloc.s V_6
IL_004c: box ""int""
IL_0051: call ""void C.Print(object, object)""
IL_0056: ldloc.s V_4
IL_0058: ldc.i4.1
IL_0059: add
IL_005a: stloc.s V_4
IL_005c: ldloc.s V_4
IL_005e: ldloc.2
IL_005f: ble.s IL_002b
IL_0061: ldloc.3
IL_0062: ldc.i4.1
IL_0063: add
IL_0064: stloc.3
IL_0065: ldloc.3
IL_0066: ldloc.1
IL_0067: ble.s IL_0020
IL_0069: ret
}");
}
[Fact]
public void ForEachStringDeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
Print(x1, x2);
}
}
static string M() { return ""123""; }
static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); }
}
static class Extension
{
public static void Deconstruct(this char value, out int item1, out int item2)
{
item1 = item2 = System.Int32.Parse(value.ToString());
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 1 - 2 2 - 3 3 - ", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 60 (0x3c)
.maxstack 3
.locals init (string V_0,
int V_1,
int V_2, //x2
int V_3,
int V_4)
IL_0000: call ""string C.M()""
IL_0005: stloc.0
IL_0006: ldc.i4.0
IL_0007: stloc.1
IL_0008: br.s IL_0032
IL_000a: ldloc.0
IL_000b: ldloc.1
IL_000c: callvirt ""char string.this[int].get""
IL_0011: ldloca.s V_3
IL_0013: ldloca.s V_4
IL_0015: call ""void Extension.Deconstruct(char, out int, out int)""
IL_001a: ldloc.3
IL_001b: ldloc.s V_4
IL_001d: stloc.2
IL_001e: box ""int""
IL_0023: ldloc.2
IL_0024: box ""int""
IL_0029: call ""void C.Print(object, object)""
IL_002e: ldloc.1
IL_002f: ldc.i4.1
IL_0030: add
IL_0031: stloc.1
IL_0032: ldloc.1
IL_0033: ldloc.0
IL_0034: callvirt ""int string.Length.get""
IL_0039: blt.s IL_000a
IL_003b: ret
}");
}
[Fact]
[WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")]
public void ForEachCollectionSymbol()
{
string source = @"
using System.Collections.Generic;
class Deconstructable
{
void M(IEnumerable<Deconstructable> x)
{
foreach (var (y1, y2) in x)
{
}
}
void Deconstruct(out int i, out int j) { i = 0; j = 0; }
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var collection = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Expression;
Assert.Equal("x", collection.ToString());
var symbol = model.GetSymbolInfo(collection).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.Equal("x", symbol.Name);
Assert.Equal("System.Collections.Generic.IEnumerable<Deconstructable> x", symbol.ToTestDisplayString());
}
[Fact]
public void ForEachIEnumerableDeclarationWithNesting()
{
string source = @"
using System.Collections.Generic;
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3), (int x4, int x5)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - "");
}
}
static IEnumerable<(int, (int, int), (int, int))> M() { yield return (1, (2, 3), (4, 5)); yield return (6, (7, 8), (9, 10)); }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionForeach(model, x3, x3Ref);
var x4 = GetDeconstructionVariable(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForDeconstructionForeach(model, x4, x4Ref);
var x5 = GetDeconstructionVariable(tree, "x5");
var x5Ref = GetReference(tree, "x5");
VerifyModelForDeconstructionForeach(model, x5, x5Ref);
// extra check on var
var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent;
Assert.Equal("var", x23Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachSZArrayDeclarationWithNesting()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3), (int x4, int x5)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - "");
}
}
static (int, (int, int), (int, int))[] M() { return new[] { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) }; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachMDArrayDeclarationWithNesting()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3), (int x4, int x5)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - "");
}
}
static (int, (int, int), (int, int))[,] M() { return new(int, (int, int), (int, int))[1, 2] { { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) } }; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachStringDeclarationWithNesting()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" - "");
}
}
static string M() { return ""12""; }
}
static class Extension
{
public static void Deconstruct(this char value, out int item1, out (int, int) item2)
{
item1 = System.Int32.Parse(value.ToString());
item2 = (item1, item1);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 1 1 - 2 2 2 - ");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructExtensionOnInterface()
{
string source = @"
public interface Interface { }
class C : Interface
{
static void Main()
{
var (x, y) = new C();
System.Console.Write($""{x} {y}"");
}
}
static class Extension
{
public static void Deconstruct(this Interface value, out int item1, out string item2)
{
item1 = 42;
item2 = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "42 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachIEnumerableDeclarationWithDeconstruct()
{
string source = @"
using System.Collections.Generic;
class C
{
static void Main()
{
foreach ((long x1, var (x2, x3)) in M())
{
Print(x1, x2, x3);
}
}
static IEnumerable<Pair<int, Pair<int, int>>> M() { yield return Pair.Create(1, Pair.Create(2, 3)); yield return Pair.Create(4, Pair.Create(5, 6)); }
static void Print(object a, object b, object c) { System.Console.WriteLine(a + "" "" + b + "" "" + c); }
}
" + commonSource;
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionForeach(model, x3, x3Ref);
// extra check on var
var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent;
Assert.Equal("var", x23Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol
};
string expected =
@"Deconstructing (1, (2, 3))
Deconstructing (2, 3)
1 2 3
Deconstructing (4, (5, 6))
Deconstructing (5, 6)
4 5 6";
var comp = CompileAndVerify(source, expectedOutput: expected, sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 90 (0x5a)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> V_0,
int V_1, //x2
int V_2, //x3
int V_3,
Pair<int, int> V_4,
int V_5,
int V_6)
IL_0000: call ""System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>> C.M()""
IL_0005: callvirt ""System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>>.GetEnumerator()""
IL_000a: stloc.0
.try
{
IL_000b: br.s IL_0045
IL_000d: ldloc.0
IL_000e: callvirt ""Pair<int, Pair<int, int>> System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>>.Current.get""
IL_0013: ldloca.s V_3
IL_0015: ldloca.s V_4
IL_0017: callvirt ""void Pair<int, Pair<int, int>>.Deconstruct(out int, out Pair<int, int>)""
IL_001c: ldloc.s V_4
IL_001e: ldloca.s V_5
IL_0020: ldloca.s V_6
IL_0022: callvirt ""void Pair<int, int>.Deconstruct(out int, out int)""
IL_0027: ldloc.3
IL_0028: conv.i8
IL_0029: ldloc.s V_5
IL_002b: stloc.1
IL_002c: ldloc.s V_6
IL_002e: stloc.2
IL_002f: box ""long""
IL_0034: ldloc.1
IL_0035: box ""int""
IL_003a: ldloc.2
IL_003b: box ""int""
IL_0040: call ""void C.Print(object, object, object)""
IL_0045: ldloc.0
IL_0046: callvirt ""bool System.Collections.IEnumerator.MoveNext()""
IL_004b: brtrue.s IL_000d
IL_004d: leave.s IL_0059
}
finally
{
IL_004f: ldloc.0
IL_0050: brfalse.s IL_0058
IL_0052: ldloc.0
IL_0053: callvirt ""void System.IDisposable.Dispose()""
IL_0058: endfinally
}
IL_0059: ret
}
");
}
[Fact]
public void ForEachSZArrayDeclarationWithDeconstruct()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3)) in M())
{
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
static Pair<int, Pair<int, int>>[] M() { return new[] { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) }; }
}
" + commonSource;
string expected =
@"Deconstructing (1, (2, 3))
Deconstructing (2, 3)
1 2 3
Deconstructing (4, (5, 6))
Deconstructing (5, 6)
4 5 6";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachMDArrayDeclarationWithDeconstruct()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3)) in M())
{
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
static Pair<int, Pair<int, int>>[,] M() { return new Pair<int, Pair<int, int>> [1, 2] { { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) } }; }
}
" + commonSource;
string expected =
@"Deconstructing (1, (2, 3))
Deconstructing (2, 3)
1 2 3
Deconstructing (4, (5, 6))
Deconstructing (5, 6)
4 5 6";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachWithExpressionBody()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in new[] { (1, 2), (3, 4) })
System.Console.Write(x1 + "" "" + x2 + "" - "");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachCreatesNewVariables()
{
string source = @"
class C
{
static void Main()
{
var lambdas = new System.Action[2];
int index = 0;
foreach (var (x1, x2) in M())
{
lambdas[index] = () => { System.Console.Write(x1 + "" ""); };
index++;
}
lambdas[0]();
lambdas[1]();
}
static (int, int)[] M() { return new[] { (0, 0), (10, 10) }; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "0 10 ");
comp.VerifyDiagnostics();
}
[Fact]
public void TupleDeconstructionIntoDynamicArrayIndexer()
{
string source = @"
class C
{
static void Main()
{
dynamic x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic x)
{
(x[0], x[1]) = (""hello"", ""world"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void IntTupleDeconstructionIntoDynamicArrayIndexer()
{
string source = @"
class C
{
static void Main()
{
dynamic x = new int[] { 1, 2 };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic x)
{
(x[0], x[1]) = (3, 4);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionIntoDynamicArrayIndexer()
{
string source = @"
class C
{
static void Main()
{
dynamic x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic x)
{
(x[0], x[1]) = new C();
}
public void Deconstruct(out string a, out string b)
{
a = ""hello"";
b = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void TupleDeconstructionIntoDynamicArray()
{
string source = @"
class C
{
static void Main()
{
dynamic[] x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic[] x)
{
(x[0], x[1]) = (""hello"", ""world"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionIntoDynamicArray()
{
string source = @"
class C
{
static void Main()
{
dynamic[] x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic[] x)
{
(x[0], x[1]) = new C();
}
public void Deconstruct(out string a, out string b)
{
a = ""hello"";
b = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionIntoDynamicMember()
{
string source = @"
class C
{
static void Main()
{
dynamic x = System.ValueTuple.Create(1, 2);
(x.Item1, x.Item2) = new C();
System.Console.WriteLine($""{x.Item1} {x.Item2}"");
}
public void Deconstruct(out int a, out int b)
{
a = 3;
b = 4;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void FieldAndLocalWithSameName()
{
string source = @"
class C
{
public int x = 3;
static void Main()
{
new C().M();
}
void M()
{
var (x, y) = (1, 2);
System.Console.Write($""{x} {y} {this.x}"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3");
comp.VerifyDiagnostics();
}
[Fact]
public void NoGlobalDeconstructionUnlessScript()
{
string source = @"
class C
{
var (x, y) = (1, 2);
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,11): error CS1001: Identifier expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(4, 11),
// (4,14): error CS1001: Identifier expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14),
// (4,16): error CS1002: ; expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(4, 16),
// (4,16): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 16),
// (4,19): error CS1031: Type expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_TypeExpected, "1").WithLocation(4, 19),
// (4,19): error CS8124: Tuple must contain at least two elements.
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_TupleTooFewElements, "1").WithLocation(4, 19),
// (4,19): error CS1026: ) expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "1").WithLocation(4, 19),
// (4,19): error CS1519: Invalid token '1' in class, record, struct, or interface member declaration
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "1").WithArguments("1").WithLocation(4, 19),
// (4,5): error CS1520: Method must have a return type
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_MemberNeedsType, "var").WithLocation(4, 5),
// (4,5): error CS0501: 'C.C(x, y)' must declare a body because it is not marked abstract, extern, or partial
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "var").WithArguments("C.C(x, y)").WithLocation(4, 5),
// (4,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(4, 10),
// (4,13): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?)
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(4, 13)
);
var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf();
Assert.False(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression));
}
[Fact]
public void SimpleDeconstructionInScript()
{
var source =
@"
using alias = System.Int32;
(string x, alias y) = (""hello"", 42);
System.Console.Write($""{x} {y}"");
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
var xRef = GetReference(tree, "x");
Assert.Equal("System.String Script.x", xSymbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x, xRef);
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, y, yRef);
// extra checks on x
var xType = GetTypeSyntax(x);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(xType).Symbol.Kind);
Assert.Equal("string", model.GetSymbolInfo(xType).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(xType));
// extra checks on y
var yType = GetTypeSyntax(y);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(yType).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(yType).Symbol.ToDisplayString());
Assert.Equal("alias=System.Int32", model.GetAliasInfo(yType).ToTestDisplayString());
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42", sourceSymbolValidator: validator);
verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 129 (0x81)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldarg.0
IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_000d: ldstr ""hello""
IL_0012: stfld ""string x""
IL_0017: ldarg.0
IL_0018: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_001d: ldc.i4.s 42
IL_001f: stfld ""int y""
IL_0024: ldstr ""{0} {1}""
IL_0029: ldarg.0
IL_002a: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_002f: ldfld ""string x""
IL_0034: ldarg.0
IL_0035: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_003a: ldfld ""int y""
IL_003f: box ""int""
IL_0044: call ""string string.Format(string, object, object)""
IL_0049: call ""void System.Console.Write(string)""
IL_004e: nop
IL_004f: ldnull
IL_0050: stloc.1
IL_0051: leave.s IL_006b
}
catch System.Exception
{
IL_0053: stloc.2
IL_0054: ldarg.0
IL_0055: ldc.i4.s -2
IL_0057: stfld ""int <<Initialize>>d__0.<>1__state""
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_0062: ldloc.2
IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)""
IL_0068: nop
IL_0069: leave.s IL_0080
}
IL_006b: ldarg.0
IL_006c: ldc.i4.s -2
IL_006e: stfld ""int <<Initialize>>d__0.<>1__state""
IL_0073: ldarg.0
IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_0079: ldloc.1
IL_007a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)""
IL_007f: nop
IL_0080: ret
}");
}
[Fact]
public void GlobalDeconstructionOutsideScript()
{
var source =
@"
(string x, int y) = (""hello"", 42);
System.Console.Write(x);
System.Console.Write(y);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf();
Assert.True(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression));
CompileAndVerify(comp, expectedOutput: "hello42");
}
[Fact]
public void NestedDeconstructionInScript()
{
var source =
@"
(string x, (int y, int z)) = (""hello"", (42, 43));
System.Console.Write($""{x} {y} {z}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43");
}
[Fact]
public void VarDeconstructionInScript()
{
var source =
@"
(var x, var y) = (""hello"", 42);
System.Console.Write($""{x} {y}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42");
}
[Fact]
public void NestedVarDeconstructionInScript()
{
var source =
@"
(var x1, var (x2, x3)) = (""hello"", (42, 43));
System.Console.Write($""{x1} {x2} {x3}"");
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.String Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
var x2Ref = GetReference(tree, "x2");
Assert.Equal("System.Int32 Script.x2", x2Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x2, x2Ref);
// extra checks on x1's var
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("string", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x1Type));
// extra check on x2 and x3's var
var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent;
Assert.Equal("var", x23Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43", sourceSymbolValidator: validator);
}
[Fact]
public void EvaluationOrderForDeconstructionInScript()
{
var source =
@"
(int, int) M(out int x) { x = 1; return (2, 3); }
var (x2, x3) = M(out var x1);
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "1 2 3");
verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 178 (0xb2)
.maxstack 4
.locals init (int V_0,
object V_1,
System.ValueTuple<int, int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldarg.0
IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_000d: ldarg.0
IL_000e: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_0013: ldflda ""int x1""
IL_0018: call ""System.ValueTuple<int, int> M(out int)""
IL_001d: stloc.2
IL_001e: ldarg.0
IL_001f: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_0024: ldloc.2
IL_0025: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002a: stfld ""int x2""
IL_002f: ldarg.0
IL_0030: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_0035: ldloc.2
IL_0036: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_003b: stfld ""int x3""
IL_0040: ldstr ""{0} {1} {2}""
IL_0045: ldarg.0
IL_0046: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_004b: ldfld ""int x1""
IL_0050: box ""int""
IL_0055: ldarg.0
IL_0056: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_005b: ldfld ""int x2""
IL_0060: box ""int""
IL_0065: ldarg.0
IL_0066: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_006b: ldfld ""int x3""
IL_0070: box ""int""
IL_0075: call ""string string.Format(string, object, object, object)""
IL_007a: call ""void System.Console.Write(string)""
IL_007f: nop
IL_0080: ldnull
IL_0081: stloc.1
IL_0082: leave.s IL_009c
}
catch System.Exception
{
IL_0084: stloc.3
IL_0085: ldarg.0
IL_0086: ldc.i4.s -2
IL_0088: stfld ""int <<Initialize>>d__0.<>1__state""
IL_008d: ldarg.0
IL_008e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_0093: ldloc.3
IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)""
IL_0099: nop
IL_009a: leave.s IL_00b1
}
IL_009c: ldarg.0
IL_009d: ldc.i4.s -2
IL_009f: stfld ""int <<Initialize>>d__0.<>1__state""
IL_00a4: ldarg.0
IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_00aa: ldloc.1
IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)""
IL_00b0: nop
IL_00b1: ret
}
");
}
[Fact]
public void DeconstructionForEachInScript()
{
var source =
@"
foreach ((string x1, var (x2, x3)) in new[] { (""hello"", (42, ""world"")) })
{
System.Console.Write($""{x1} {x2} {x3}"");
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x1Symbol.Kind);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x2Symbol.Kind);
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator);
}
[Fact]
public void DeconstructionInForLoopInScript()
{
var source =
@"
for ((string x1, var (x2, x3)) = (""hello"", (42, ""world"")); ; )
{
System.Console.Write($""{x1} {x2} {x3}"");
break;
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x1Symbol.Kind);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x2Symbol.Kind);
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator);
}
[Fact]
public void DeconstructionInCSharp6Script()
{
var source =
@"
var (x, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6), options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,5): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x, y)").WithArguments("tuples", "7.0").WithLocation(2, 5),
// (2,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7 or greater.
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(2, 14)
);
}
[Fact]
public void InvalidDeconstructionInScript()
{
var source =
@"
int (x, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// int (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 5)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString());
var xType = ((IFieldSymbol)xSymbol).Type;
Assert.False(xType.IsErrorType());
Assert.Equal("System.Int32", xType.ToTestDisplayString());
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString());
var yType = ((IFieldSymbol)ySymbol).Type;
Assert.False(yType.IsErrorType());
Assert.Equal("System.Int32", yType.ToTestDisplayString());
}
[Fact]
public void InvalidDeconstructionInScript_2()
{
var source =
@"
(int (x, y), int z) = ((1, 2), 3);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,6): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// (int (x, y), int z) = ((1, 2), 3);
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 6)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString());
var xType = ((IFieldSymbol)xSymbol).Type;
Assert.False(xType.IsErrorType());
Assert.Equal("System.Int32", xType.ToTestDisplayString());
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString());
var yType = ((IFieldSymbol)ySymbol).Type;
Assert.False(yType.IsErrorType());
Assert.Equal("System.Int32", yType.ToTestDisplayString());
}
[Fact]
public void NameConflictInDeconstructionInScript()
{
var source =
@"
int x1;
var (x1, x2) = (1, 2);
System.Console.Write(x1);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (3,6): error CS0102: The type 'Script' already contains a definition for 'x1'
// var (x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x1").WithArguments("Script", "x1").WithLocation(3, 6),
// (4,22): error CS0229: Ambiguity between 'x1' and 'x1'
// System.Console.Write(x1);
Diagnostic(ErrorCode.ERR_AmbigMember, "x1").WithArguments("x1", "x1").WithLocation(4, 22)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var firstX1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "x1").Single();
var firstX1Symbol = model.GetDeclaredSymbol(firstX1);
Assert.Equal("System.Int32 Script.x1", firstX1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, firstX1Symbol.Kind);
var secondX1 = GetDeconstructionVariable(tree, "x1");
var secondX1Symbol = model.GetDeclaredSymbol(secondX1);
Assert.Equal("System.Int32 Script.x1", secondX1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, secondX1Symbol.Kind);
Assert.NotEqual(firstX1Symbol, secondX1Symbol);
}
[Fact]
public void NameConflictInDeconstructionInScript2()
{
var source =
@"
var (x, y) = (1, 2);
var (z, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (3,9): error CS0102: The type 'Script' already contains a definition for 'y'
// var (z, y) = (1, 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "y").WithArguments("Script", "y").WithLocation(3, 9)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var firstY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").First();
var firstYSymbol = model.GetDeclaredSymbol(firstY);
Assert.Equal("System.Int32 Script.y", firstYSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, firstYSymbol.Kind);
var secondY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").ElementAt(1);
var secondYSymbol = model.GetDeclaredSymbol(secondY);
Assert.Equal("System.Int32 Script.y", secondYSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, secondYSymbol.Kind);
Assert.NotEqual(firstYSymbol, secondYSymbol);
}
[Fact]
public void NameConflictInDeconstructionInScript3()
{
var source =
@"
var (x, (y, x)) = (1, (2, ""hello""));
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,13): error CS0102: The type 'Script' already contains a definition for 'x'
// var (x, (y, x)) = (1, (2, "hello"));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("Script", "x").WithLocation(2, 13)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var firstX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").First();
var firstXSymbol = model.GetDeclaredSymbol(firstX);
Assert.Equal("System.Int32 Script.x", firstXSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, firstXSymbol.Kind);
var secondX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").ElementAt(1);
var secondXSymbol = model.GetDeclaredSymbol(secondX);
Assert.Equal("System.String Script.x", secondXSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, secondXSymbol.Kind);
Assert.NotEqual(firstXSymbol, secondXSymbol);
}
[Fact]
public void UnassignedUsedInDeconstructionInScript()
{
var source =
@"
System.Console.Write(x);
var (x, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
var xRef = GetReference(tree, "x");
Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x, xRef);
var xType = ((IFieldSymbol)xSymbol).Type;
Assert.False(xType.IsErrorType());
Assert.Equal("System.Int32", xType.ToTestDisplayString());
}
[Fact]
public void FailedInferenceInDeconstructionInScript()
{
var source =
@"
var (x, y) = (1, null);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.GetDeclarationDiagnostics().Verify(
// (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6),
// (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9)
);
comp.VerifyDiagnostics(
// (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6),
// (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
Assert.Equal("var Script.x", xSymbol.ToTestDisplayString());
var xType = xSymbol.GetSymbol<FieldSymbol>().TypeWithAnnotations;
Assert.True(xType.Type.IsErrorType());
Assert.Equal("var", xType.ToTestDisplayString());
var xTypeISymbol = xType.Type.GetPublicSymbol();
Assert.Equal(SymbolKind.ErrorType, xTypeISymbol.Kind);
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
Assert.Equal("var Script.y", ySymbol.ToTestDisplayString());
var yType = ((IFieldSymbol)ySymbol).Type;
Assert.True(yType.IsErrorType());
Assert.Equal("var", yType.ToTestDisplayString());
}
[Fact]
public void FailedCircularInferenceInDeconstructionInScript()
{
var source =
@"
var (x1, x2) = (x2, x1);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.GetDeclarationDiagnostics().Verify(
// (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (x2, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10),
// (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (x2, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x1Type = ((IFieldSymbol)x1Symbol).Type;
Assert.True(x1Type.IsErrorType());
Assert.Equal("var", x1Type.Name);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
var x2Ref = GetReference(tree, "x2");
Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x2, x2Ref);
var x2Type = ((IFieldSymbol)x2Symbol).Type;
Assert.True(x2Type.IsErrorType());
Assert.Equal("var", x2Type.Name);
}
[Fact]
public void FailedCircularInferenceInDeconstructionInScript2()
{
var source =
@"
var (x1, x2) = (y1, y2);
var (y1, y2) = (x1, x2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.GetDeclarationDiagnostics().Verify(
// (3,6): error CS7019: Type of 'y1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (y1, y2) = (x1, x2);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "y1").WithArguments("y1").WithLocation(3, 6),
// (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (y1, y2);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6),
// (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (y1, y2);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x1Type = ((IFieldSymbol)x1Symbol).Type;
Assert.True(x1Type.IsErrorType());
Assert.Equal("var", x1Type.Name);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
var x2Ref = GetReference(tree, "x2");
Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x2, x2Ref);
var x2Type = ((IFieldSymbol)x2Symbol).Type;
Assert.True(x2Type.IsErrorType());
Assert.Equal("var", x2Type.Name);
}
[Fact]
public void VarAliasInVarDeconstructionInScript()
{
var source =
@"
using var = System.Byte;
var (x1, (x2, x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (3,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// var (x1, (x2, x3)) = (1, (2, 3));
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(3, 5)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra check on var
var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x123Var.Type.ToString());
Assert.Null(model.GetTypeInfo(x123Var.Type).Type);
Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
}
[Fact]
public void VarTypeInVarDeconstructionInScript()
{
var source =
@"
class var
{
public static implicit operator var(int i) { return null; }
}
var (x1, (x2, x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (6,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// var (x1, (x2, x3)) = (1, (2, 3));
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(6, 5)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra check on var
var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x123Var.Type.ToString());
Assert.Null(model.GetTypeInfo(x123Var.Type).Type);
Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
}
[Fact]
public void VarAliasInTypedDeconstructionInScript()
{
var source =
@"
using var = System.Byte;
(var x1, (var x2, var x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2 3");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra checks on x1's var
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("byte", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
var x1Alias = model.GetAliasInfo(x1Type);
Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind);
Assert.Equal("byte", x1Alias.Target.ToDisplayString());
// extra checks on x3's var
var x3Type = GetTypeSyntax(x3);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind);
Assert.Equal("byte", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString());
var x3Alias = model.GetAliasInfo(x3Type);
Assert.Equal(SymbolKind.NamedType, x3Alias.Target.Kind);
Assert.Equal("byte", x3Alias.Target.ToDisplayString());
}
[Fact]
public void VarTypeInTypedDeconstructionInScript()
{
var source =
@"
class var
{
public static implicit operator var(int i) { return new var(); }
public override string ToString() { return ""var""; }
}
(var x1, (var x2, var x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "var var var");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x1).Symbol);
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x3).Symbol);
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra checks on x1's var
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x1Type));
// extra checks on x3's var
var x3Type = GetTypeSyntax(x3);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x3Type));
}
[Fact]
public void SimpleDiscardWithConversion()
{
var source =
@"
class C
{
static void Main()
{
(int _, var x) = (new C(1), 1);
(var _, var y) = (new C(2), 2);
var (_, z) = (new C(3), 3);
System.Console.Write($""Output {x} {y} {z}."");
}
int _i;
public C(int i) { _i = i; }
public static implicit operator int(C c) { System.Console.Write($""Converted {c._i}. ""); return 0; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "Converted 1. Output 1 2 3.");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("C", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardDesignations(tree).ElementAt(2);
var declaration3 = (DeclarationExpressionSyntax)discard3.Parent.Parent;
Assert.Equal("var (_, z)", declaration3.ToString());
Assert.Equal("(C, System.Int32 z)", model.GetTypeInfo(declaration3).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration3).Symbol);
}
[Fact]
public void CannotDeconstructIntoDiscardOfWrongType()
{
var source =
@"
class C
{
static void Main()
{
(int _, string _) = (""hello"", 42);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,30): error CS0029: Cannot implicitly convert type 'string' to 'int'
// (int _, string _) = ("hello", 42);
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int").WithLocation(6, 30),
// (6,39): error CS0029: Cannot implicitly convert type 'int' to 'string'
// (int _, string _) = ("hello", 42);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(6, 39)
);
}
[Fact]
public void DiscardFromDeconstructMethod()
{
var source =
@"
class C
{
static void Main()
{
(var _, string y) = new C();
System.Console.Write(y);
}
void Deconstruct(out int x, out string y) { x = 42; y = ""hello""; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "hello");
}
[Fact]
public void ShortDiscardInDeclaration()
{
var source =
@"
class C
{
static void Main()
{
(_, var x) = (1, 2);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard = GetDiscardIdentifiers(tree).First();
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString());
var isymbol = (ISymbol)symbol;
Assert.Equal(SymbolKind.Discard, isymbol.Kind);
}
[Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")]
public void SameTypeDiscardsAreEqual01()
{
var source =
@"
class C
{
static void Main()
{
(_, _) = (1, 2);
_ = 3;
M(out _);
}
static void M(out int x) => x = 1;
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discards = GetDiscardIdentifiers(tree).ToArray();
Assert.Equal(4, discards.Length);
var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol;
Assert.Equal(symbol0, symbol0);
var set = new HashSet<ISymbol>();
foreach (var discard in discards)
{
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
set.Add(symbol);
Assert.Equal(SymbolKind.Discard, symbol.Kind);
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol0, symbol);
Assert.Equal(symbol, symbol);
Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode());
// Test to show that reference-unequal discards are equal by type.
IDiscardSymbol symbolClone = new DiscardSymbol(TypeWithAnnotations.Create(symbol.Type.GetSymbol())).GetPublicSymbol();
Assert.NotSame(symbol, symbolClone);
Assert.Equal(SymbolKind.Discard, symbolClone.Kind);
Assert.Equal("int _", symbolClone.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol.Type, symbolClone.Type);
Assert.Equal(symbol0, symbolClone);
Assert.Equal(symbol, symbolClone);
Assert.Same(symbol.Type, symbolClone.Type); // original symbol for System.Int32 has identity.
Assert.Equal(symbol.GetHashCode(), symbolClone.GetHashCode());
}
Assert.Equal(1, set.Count);
}
[Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")]
public void SameTypeDiscardsAreEqual02()
{
var source =
@"using System.Collections.Generic;
class C
{
static void Main()
{
(_, _) = (new List<int>(), new List<int>());
_ = new List<int>();
M(out _);
}
static void M(out List<int> x) => x = new List<int>();
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discards = GetDiscardIdentifiers(tree).ToArray();
Assert.Equal(4, discards.Length);
var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol;
Assert.Equal(symbol0, symbol0);
var set = new HashSet<ISymbol>();
foreach (var discard in discards)
{
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
set.Add(symbol);
Assert.Equal(SymbolKind.Discard, symbol.Kind);
Assert.Equal("List<int> _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol0, symbol);
Assert.Equal(symbol0.Type, symbol.Type);
Assert.Equal(symbol, symbol);
Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode());
if (discard != discards[0])
{
// Although it is not part of the compiler's contract, at the moment distinct constructions are distinct
Assert.NotSame(symbol.Type, symbol0.Type);
Assert.NotSame(symbol, symbol0);
}
}
Assert.Equal(1, set.Count);
}
[Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")]
public void DifferentTypeDiscardsAreNotEqual()
{
var source =
@"
class C
{
static void Main()
{
(_, _) = (1.0, 2);
_ = 3;
M(out _);
}
static void M(out int x) => x = 1;
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discards = GetDiscardIdentifiers(tree).ToArray();
Assert.Equal(4, discards.Length);
var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol;
var set = new HashSet<ISymbol>();
foreach (var discard in discards)
{
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal(SymbolKind.Discard, symbol.Kind);
set.Add(symbol);
if (discard == discards[0])
{
Assert.Equal("double _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol0, symbol);
Assert.Equal(symbol0.GetHashCode(), symbol.GetHashCode());
}
else
{
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.NotEqual(symbol0, symbol);
}
}
Assert.Equal(2, set.Count);
}
[Fact]
public void EscapedUnderscoreInDeclaration()
{
var source =
@"
class C
{
static void Main()
{
(@_, var x) = (1, 2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (6,10): error CS0103: The name '_' does not exist in the current context
// (@_, var x) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
Assert.Empty(GetDiscardIdentifiers(tree));
}
[Fact]
public void EscapedUnderscoreInDeclarationCSharp9()
{
var source =
@"
class C
{
static void Main()
{
(@_, var x) = (1, 2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (@_, var x) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(@_, var x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9),
// (6,10): error CS0103: The name '_' does not exist in the current context
// (@_, var x) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
Assert.Empty(GetDiscardIdentifiers(tree));
}
[Fact]
public void UnderscoreLocalInDeconstructDeclaration()
{
var source =
@"
class C
{
static void Main()
{
int _;
(_, var x) = (1, 2);
System.Console.Write(_);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1")
.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int V_0, //_
int V_1) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldloc.0
IL_0006: call ""void System.Console.Write(int)""
IL_000b: nop
IL_000c: ret
}");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard = GetDiscardIdentifiers(tree).First();
Assert.Equal("(_, var x)", discard.Parent.Parent.ToString());
var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString());
}
[Fact]
public void ShortDiscardInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int x;
(_, _, x) = (1, 2, 3);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "3");
}
[Fact]
public void DiscardInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int x;
(_, x) = (1L, 2);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Equal("long _", model.GetSymbolInfo(discard1).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
var tuple1 = (TupleExpressionSyntax)discard1.Parent.Parent;
Assert.Equal("(_, x)", tuple1.ToString());
Assert.Equal("(System.Int64, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(tuple1).Symbol);
}
[Fact]
public void DiscardInDeconstructDeclaration()
{
var source =
@"
class C
{
static void Main()
{
var (_, x) = (1, 2);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
var tuple1 = (DeclarationExpressionSyntax)discard1.Parent.Parent;
Assert.Equal("var (_, x)", tuple1.ToString());
Assert.Equal("(System.Int32, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString());
}
[Fact]
public void UnderscoreLocalInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int x, _;
(_, x) = (1, 2);
System.Console.Write($""{_} {x}"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard = GetDiscardIdentifiers(tree).First();
Assert.Equal("(_, x)", discard.Parent.Parent.ToString());
var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
public void DiscardInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach (var (_, x) in new[] { (1, ""hello"") }) { System.Console.Write(""1 ""); }
foreach ((_, (var y, int z)) in new[] { (1, (""hello"", 2)) }) { System.Console.Write(""2""); }
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
DiscardDesignationSyntax discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetTypeInfo(discard1).Type);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent.Parent;
Assert.Equal("var (_, x)", declaration1.ToString());
Assert.Null(model.GetTypeInfo(discard1).Type);
Assert.Equal("(System.Int32, System.String x)", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
IdentifierNameSyntax discard2 = GetDiscardIdentifiers(tree).First();
Assert.Equal("(_, (var y, int z))", discard2.Parent.Parent.ToString());
Assert.Equal("int _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.Int32", model.GetTypeInfo(discard2).Type.ToTestDisplayString());
var yz = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2);
Assert.Equal("(var y, int z)", yz.ToString());
Assert.Equal("(System.String y, System.Int32 z)", model.GetTypeInfo(yz).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(yz).Symbol);
var y = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1);
Assert.Equal("var y", y.ToString());
Assert.Equal("System.String", model.GetTypeInfo(y).Type.ToTestDisplayString());
Assert.Equal("System.String y", model.GetSymbolInfo(y).Symbol.ToTestDisplayString());
}
[Fact]
public void TwoDiscardsInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach ((_, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2""); }
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var refs = GetReferences(tree, "_");
Assert.Equal(2, refs.Count());
model.GetTypeInfo(refs.ElementAt(0)); // Assert.Equal("int", model.GetTypeInfo(refs.ElementAt(0)).Type.ToDisplayString());
model.GetTypeInfo(refs.ElementAt(1)); // Assert.Equal("string", model.GetTypeInfo(refs.ElementAt(1)).Type.ToDisplayString());
var tuple = (TupleExpressionSyntax)refs.ElementAt(0).Parent.Parent;
Assert.Equal("(_, _)", tuple.ToString());
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: @"2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics(
// this is permitted now, as it is just an assignment expression
);
}
[Fact]
public void UnderscoreLocalDisallowedInForEach()
{
var source =
@"
class C
{
static void Main()
{
{
foreach ((var x, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2 ""); }
}
{
int _;
foreach ((var y, _) in new[] { (1, ""hello"") }) { System.Console.Write(""4""); } // error
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (11,30): error CS0029: Cannot implicitly convert type 'string' to 'int'
// foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error
Diagnostic(ErrorCode.ERR_NoImplicitConv, "_").WithArguments("string", "int").WithLocation(11, 30),
// (11,22): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var y, _)").WithLocation(11, 22),
// (10,17): warning CS0168: The variable '_' is declared but never used
// int _;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(10, 17)
);
}
[Fact]
public void TwoDiscardsInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
(_, _) = (new C(), new C());
}
public C() { System.Console.Write(""C""); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
}
[Fact]
public void VerifyDiscardIL()
{
var source =
@"
class C
{
C()
{
System.Console.Write(""ctor"");
}
static int Main()
{
var (x, _, _) = (1, new C(), 2);
return x;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "ctor");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main()", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: newobj ""C..ctor()""
IL_0005: pop
IL_0006: ldc.i4.1
IL_0007: ret
}");
}
[Fact]
public void SingleDiscardInAssignment()
{
var source =
@"
class C
{
static void Main()
{
_ = M();
}
public static int M() { System.Console.Write(""M""); return 1; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "M");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Equal("System.Int32", model.GetTypeInfo(discard1).Type.ToTestDisplayString());
}
[Fact]
public void SingleDiscardInAssignmentInCSharp6()
{
var source =
@"
class C
{
static void Error()
{
_ = 1;
}
static void Ok()
{
int _;
_ = 1;
System.Console.Write(_);
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6);
comp.VerifyDiagnostics(
// (6,9): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater.
// _ = 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 9)
);
}
[Fact]
public void VariousDiscardsInCSharp6()
{
var source =
@"
class C
{
static void M1(out int x)
{
(_, var _, int _) = (1, 2, 3);
var (_, _) = (1, 2);
bool b = 3 is int _;
switch (3)
{
case int _:
break;
}
M1(out var _);
M1(out int _);
M1(out _);
x = 2;
}
static void M2()
{
const int _ = 3;
switch (3)
{
case _: // not a discard
break;
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6);
comp.VerifyDiagnostics(
// (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// (_, var _, int _) = (1, 2, 3);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, var _, int _)").WithArguments("tuples", "7.0").WithLocation(6, 9),
// (6,10): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater.
// (_, var _, int _) = (1, 2, 3);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 10),
// (6,29): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// (_, var _, int _) = (1, 2, 3);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2, 3)").WithArguments("tuples", "7.0").WithLocation(6, 29),
// (7,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (_, _) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, _)").WithArguments("tuples", "7.0").WithLocation(7, 13),
// (7,22): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (_, _) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(7, 22),
// (8,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater.
// bool b = 3 is int _;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is int _").WithArguments("pattern matching", "7.0").WithLocation(8, 18),
// (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater.
// case int _:
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case int _:").WithArguments("pattern matching", "7.0").WithLocation(11, 13),
// (14,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// M1(out var _);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(14, 20),
// (15,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// M1(out int _);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(15, 20),
// (16,16): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater.
// M1(out _);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(16, 16),
// (24,18): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.
// case _: // not a discard
Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(24, 18)
);
}
[Fact]
public void SingleDiscardInAsyncAssignment()
{
var source =
@"
class C
{
async void M()
{
System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // warning
_ = System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // fire-and-forget
await System.Threading.Tasks.Task.Delay(new System.TimeSpan(0));
}
}
";
var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,9): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
// System.Threading.Tasks.Task.Delay(new System.TimeSpan(0));
Diagnostic(ErrorCode.WRN_UnobservedAwaitableExpression, "System.Threading.Tasks.Task.Delay(new System.TimeSpan(0))").WithLocation(6, 9)
);
}
[Fact]
public void SingleDiscardInUntypedAssignment()
{
var source =
@"
class C
{
static void Main()
{
_ = null;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS8183: Cannot infer the type of implicitly-typed discard.
// _ = null;
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9)
);
}
[Fact]
public void UnderscoreLocalInAssignment()
{
var source =
@"
class C
{
static void Main()
{
int _;
_ = M();
System.Console.Write(_);
}
public static int M() { return 1; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1");
}
[Fact]
public void DeclareAndUseLocalInDeconstruction()
{
var source =
@"
class C
{
static void Main()
{
(var x, x) = (1, 2);
(y, var y) = (1, 2);
}
}
";
var compCSharp9 = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compCSharp9.VerifyDiagnostics(
// (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (var x, x) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(var x, x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9),
// (6,17): error CS0841: Cannot use local variable 'x' before it is declared
// (var x, x) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17),
// (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (y, var y) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(y, var y) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9),
// (7,10): error CS0841: Cannot use local variable 'y' before it is declared
// (y, var y) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10)
);
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (6,17): error CS0841: Cannot use local variable 'x' before it is declared
// (var x, x) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17),
// (7,10): error CS0841: Cannot use local variable 'y' before it is declared
// (y, var y) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10)
);
}
[Fact]
public void OutVarAndUsageInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
(M(out var x).P, x) = (1, x);
System.Console.Write(x);
}
static C M(out int i) { i = 42; return new C(); }
int P { set { System.Console.Write($""Written {value}. ""); } }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,26): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (M(out var x).P, x) = (1, x);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(6, 26)
);
CompileAndVerify(comp, expectedOutput: "Written 1. 42");
}
[Fact]
public void OutDiscardInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int _;
(M(out var _).P, _) = (1, 2);
System.Console.Write(_);
}
static C M(out int i) { i = 42; return new C(); }
int P { set { System.Console.Write($""Written {value}. ""); } }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "Written 1. 2");
}
[Fact]
public void OutDiscardInDeconstructTarget()
{
var source =
@"
class C
{
static void Main()
{
(x, _) = (M(out var x), 2);
System.Console.Write(x);
}
static int M(out int i) { i = 42; return 3; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,10): error CS0841: Cannot use local variable 'x' before it is declared
// (x, _) = (M(out var x), 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 10)
);
}
[Fact]
public void SimpleDiscardDeconstructInScript()
{
var source =
@"
using alias = System.Int32;
(string _, alias _) = (""hello"", 42);
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("string _", declaration1.ToString());
Assert.Null(model.GetDeclaredSymbol(declaration1));
Assert.Null(model.GetDeclaredSymbol(discard1));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("alias _", declaration2.ToString());
Assert.Null(model.GetDeclaredSymbol(declaration2));
Assert.Null(model.GetDeclaredSymbol(discard2));
var tuple = (TupleExpressionSyntax)declaration1.Parent.Parent;
Assert.Equal("(string _, alias _)", tuple.ToString());
Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString());
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, sourceSymbolValidator: validator);
}
[Fact]
public void SimpleDiscardDeconstructInScript2()
{
var source =
@"
public class C
{
public C() { System.Console.Write(""ctor""); }
public void Deconstruct(out string x, out string y) { x = y = null; }
}
(string _, string _) = new C();
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor");
}
[Fact]
public void SingleDiscardInAssignmentInScript()
{
var source =
@"
int M() { System.Console.Write(""M""); return 1; }
_ = M();
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "M");
}
[Fact]
public void NestedVarDiscardDeconstructionInScript()
{
var source =
@"
(var _, var (_, x3)) = (""hello"", (42, 43));
System.Console.Write($""{x3}"");
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
var nestedDeclaration = (DeclarationExpressionSyntax)discard2.Parent.Parent;
Assert.Equal("var (_, x3)", nestedDeclaration.ToString());
Assert.Null(model.GetDeclaredSymbol(nestedDeclaration));
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Equal("(System.Int32, System.Int32 x3)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol);
var tuple = (TupleExpressionSyntax)discard2.Parent.Parent.Parent.Parent;
Assert.Equal("(var _, var (_, x3))", tuple.ToString());
Assert.Equal("(System.String, (System.Int32, System.Int32 x3))", model.GetTypeInfo(tuple).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(tuple).Symbol);
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "43", sourceSymbolValidator: validator);
}
[Fact]
public void VariousDiscardsInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach ((var _, int _, _, var (_, _), int x) in new[] { (1L, 2, 3, (""hello"", 5), 6) })
{
System.Console.Write(x);
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "6");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.True(model.GetSymbolInfo(discard1).IsEmpty);
Assert.Null(model.GetTypeInfo(discard1).Type);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("var _", declaration1.ToString());
Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.True(model.GetSymbolInfo(discard2).IsEmpty);
Assert.Null(model.GetTypeInfo(discard2).Type);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("int _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Equal("_", discard3.Parent.ToString());
Assert.Null(model.GetDeclaredSymbol(discard3));
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
Assert.Equal("int _", model.GetSymbolInfo(discard3).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
var discard4 = GetDiscardDesignations(tree).ElementAt(2);
Assert.Null(model.GetDeclaredSymbol(discard4));
Assert.True(model.GetSymbolInfo(discard4).IsEmpty);
Assert.Null(model.GetTypeInfo(discard4).Type);
var nestedDeclaration = (DeclarationExpressionSyntax)discard4.Parent.Parent;
Assert.Equal("var (_, _)", nestedDeclaration.ToString());
Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol);
}
[Fact]
public void UnderscoreInCSharp6Foreach()
{
var source =
@"
class C
{
static void Main()
{
foreach (var _ in M())
{
System.Console.Write(_);
}
}
static System.Collections.Generic.IEnumerable<int> M()
{
System.Console.Write(""M "");
yield return 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "M 1");
}
[Fact]
public void ShortDiscardDisallowedInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach (_ in M())
{
}
}
static System.Collections.Generic.IEnumerable<int> M()
{
yield return 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach (_ in M())
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 18)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var discard = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().First();
var symbol = (DiscardSymbol)model.GetSymbolInfo(discard).Symbol.GetSymbol();
Assert.True(symbol.TypeWithAnnotations.Type.IsErrorType());
}
[Fact]
public void ExistingUnderscoreLocalInLegacyForeach()
{
var source =
@"
class C
{
static void Main()
{
int _;
foreach (var _ in new[] { 1 })
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,22): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var _ in new[] { 1 })
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(7, 22),
// (6,13): warning CS0168: The variable '_' is declared but never used
// int _;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 13)
);
}
[Fact]
public void MixedDeconstruction_01()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
var x = (int x1, int x2) = t;
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (7,18): error CS8185: A declaration is not allowed in this context.
// var x = (int x1, int x2) = t;
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
}
[Fact]
public void MixedDeconstruction_02()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
int z;
(int x1, z) = t;
System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "1")
.VerifyIL("Program.Main", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (System.ValueTuple<int, int> V_0, //t
int V_1, //z
int V_2) //x1
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.0
IL_000b: dup
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: stloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0017: stloc.1
IL_0018: ldloc.2
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: nop
IL_001f: ret
}");
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
}
[Fact]
public void MixedDeconstruction_03()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
int z;
for ((int x1, z) = t; ; )
{
System.Console.WriteLine(x1);
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "1")
.VerifyIL("Program.Main", @"
{
// Code size 39 (0x27)
.maxstack 3
.locals init (System.ValueTuple<int, int> V_0, //t
int V_1, //z
int V_2) //x1
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.0
IL_000b: dup
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: stloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0017: stloc.1
IL_0018: br.s IL_0024
IL_001a: nop
IL_001b: ldloc.2
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: nop
IL_0022: br.s IL_0026
IL_0024: br.s IL_001a
IL_0026: ret
}");
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var symbolInfo = model.GetSymbolInfo(x1Ref);
Assert.Equal(symbolInfo.Symbol, model.GetDeclaredSymbol(x1));
Assert.Equal(SpecialType.System_Int32, symbolInfo.Symbol.GetTypeOrReturnType().SpecialType);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(int x1, z)", lhs.ToString());
Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
}
[Fact]
public void MixedDeconstruction_03CSharp9()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
int z;
for ((int x1, z) = t; ; )
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (8,14): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// for ((int x1, z) = t; ; )
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, z) = t").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 14));
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
}
[Fact]
public void MixedDeconstruction_04()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
for (; ; (int x1, int x2) = t)
{
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8185: A declaration is not allowed in this context.
// for (; ; (int x1, int x2) = t)
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 19),
// (9,38): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(9, 38),
// (10,38): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(10, 38)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1);
var symbolInfo = model.GetSymbolInfo(x1Ref);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2);
symbolInfo = model.GetSymbolInfo(x2Ref);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
}
[Fact]
public void MixedDeconstruction_05()
{
string source = @"
class Program
{
static void Main(string[] args)
{
foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
{
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
static int _M;
static ref int M(out int x) { x = 2; return ref _M; }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "args is var x2").WithLocation(6, 34),
// (6,34): error CS0029: Cannot implicitly convert type 'int' to 'bool'
// foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
Diagnostic(ErrorCode.ERR_NoImplicitConv, "args is var x2").WithArguments("int", "bool").WithLocation(6, 34),
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(M(out var x1), args is var x2, _)").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString());
model = compilation.GetSemanticModel(tree);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.Equal("string[]", model.GetTypeInfo(x2Ref).Type.ToDisplayString());
VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref);
VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref);
}
[Fact]
public void ForeachIntoExpression()
{
string source = @"
class Program
{
static void Main(string[] args)
{
foreach (M(out var x1) in new[] { 1, 2, 3 })
{
System.Console.WriteLine(x1);
}
}
static int _M;
static ref int M(out int x) { x = 2; return ref _M; }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,32): error CS0230: Type and identifier are both required in a foreach statement
// foreach (M(out var x1) in new[] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 32)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString());
VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref);
}
[Fact]
public void MixedDeconstruction_06()
{
string source = @"
class Program
{
static void Main(string[] args)
{
foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3})
{
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
static int _M;
static ref int M1(int m2, int x, string[] y) { return ref _M; }
static int M2(out int x, bool b) => x = 2;
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,61): error CS0230: Type and identifier are both required in a foreach statement
// foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3})
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 61)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref.First()).Type.ToDisplayString());
model = compilation.GetSemanticModel(tree);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReferences(tree, "x2");
Assert.Equal("string[]", model.GetTypeInfo(x2Ref.First()).Type.ToDisplayString());
VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref.ToArray());
VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref.ToArray());
}
[Fact]
public void MixedDeconstruction_07()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, ("""", true));
string y;
for ((int x, (y, var z)) = t; ; )
{
System.Console.Write(x);
System.Console.Write(z);
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
CompileAndVerify(compilation, expectedOutput: "1True")
.VerifyIL("Program.Main", @"
{
// Code size 73 (0x49)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<string, bool>> V_0, //t
string V_1, //y
int V_2, //x
bool V_3, //z
System.ValueTuple<string, bool> V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldstr """"
IL_0009: ldc.i4.1
IL_000a: newobj ""System.ValueTuple<string, bool>..ctor(string, bool)""
IL_000f: call ""System.ValueTuple<int, System.ValueTuple<string, bool>>..ctor(int, System.ValueTuple<string, bool>)""
IL_0014: ldloc.0
IL_0015: dup
IL_0016: ldfld ""System.ValueTuple<string, bool> System.ValueTuple<int, System.ValueTuple<string, bool>>.Item2""
IL_001b: stloc.s V_4
IL_001d: ldfld ""int System.ValueTuple<int, System.ValueTuple<string, bool>>.Item1""
IL_0022: stloc.2
IL_0023: ldloc.s V_4
IL_0025: ldfld ""string System.ValueTuple<string, bool>.Item1""
IL_002a: stloc.1
IL_002b: ldloc.s V_4
IL_002d: ldfld ""bool System.ValueTuple<string, bool>.Item2""
IL_0032: stloc.3
IL_0033: br.s IL_0046
IL_0035: nop
IL_0036: ldloc.2
IL_0037: call ""void System.Console.Write(int)""
IL_003c: nop
IL_003d: ldloc.3
IL_003e: call ""void System.Console.Write(bool)""
IL_0043: nop
IL_0044: br.s IL_0048
IL_0046: br.s IL_0035
IL_0048: ret
}");
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xRef = GetReference(tree, "x");
VerifyModelForDeconstructionLocal(model, x, xRef);
var xSymbolInfo = model.GetSymbolInfo(xRef);
Assert.Equal(xSymbolInfo.Symbol, model.GetDeclaredSymbol(x));
Assert.Equal(SpecialType.System_Int32, xSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType);
var z = GetDeconstructionVariable(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForDeconstructionLocal(model, z, zRef);
var zSymbolInfo = model.GetSymbolInfo(zRef);
Assert.Equal(zSymbolInfo.Symbol, model.GetDeclaredSymbol(z));
Assert.Equal(SpecialType.System_Boolean, zSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2);
Assert.Equal(@"(int x, (y, var z))", lhs.ToString());
Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
}
[Fact]
public void IncompleteDeclarationIsSeenAsTupleLiteral()
{
string source = @"
class C
{
static void Main()
{
(int x1, string x2);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 10),
// (6,18): error CS8185: A declaration is not allowed in this context.
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string x2").WithLocation(6, 18),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x1, string x2)").WithLocation(6, 9),
// (6,10): error CS0165: Use of unassigned local variable 'x1'
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 10),
// (6,18): error CS0165: Use of unassigned local variable 'x2'
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "string x2").WithArguments("x2").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString());
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.Equal("string", model.GetTypeInfo(x2Ref).Type.ToDisplayString());
VerifyModelForDeconstruction(model, x1, LocalDeclarationKind.DeclarationExpressionVariable, x1Ref);
VerifyModelForDeconstruction(model, x2, LocalDeclarationKind.DeclarationExpressionVariable, x2Ref);
}
[Fact]
[WorkItem(15893, "https://github.com/dotnet/roslyn/issues/15893")]
public void DeconstructionOfOnlyOneElement()
{
string source = @"
class C
{
static void Main()
{
var (p2) = (1, 2);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,16): error CS1003: Syntax error, ',' expected
// var (p2) = (1, 2);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(6, 16),
// (6,16): error CS1001: Identifier expected
// var (p2) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 16)
);
}
[Fact]
[WorkItem(14876, "https://github.com/dotnet/roslyn/issues/14876")]
public void TupleTypeInDeconstruction()
{
string source = @"
class C
{
static void Main()
{
(int x, (string, long) y) = M();
System.Console.Write($""{x} {y}"");
}
static (int, (string, long)) M()
{
return (5, (""Goo"", 34983490));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "5 (Goo, 34983490)");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")]
public void RefReturningVarInvocation()
{
string source = @"
class C
{
static int i;
static void Main()
{
int x = 0, y = 0;
(var(x, y)) = 42; // parsed as invocation
System.Console.Write(i);
}
static ref int var(int a, int b) { return ref i; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "42", verify: Verification.Passes);
comp.VerifyDiagnostics();
}
[Fact]
void InvokeVarForLvalueInParens()
{
var source = @"
class Program
{
public static void Main()
{
(var(x, y)) = 10;
System.Console.WriteLine(z);
}
static int x = 1, y = 2, z = 3;
static ref int var(int x, int y)
{
return ref z;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
// PEVerify fails with ref return https://github.com/dotnet/roslyn/issues/12285
CompileAndVerify(compilation, expectedOutput: "10", verify: Verification.Fails);
}
[Fact]
[WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")]
public void DefAssignmentsStruct001()
{
string source = @"
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
((int, int), string)[] arr = new((int, int), string)[1];
Test5(arr);
}
public static void Test4(IEnumerable<(KeyValuePair<int, int>, string)> en)
{
foreach ((KeyValuePair<int, int> kv, string s) in en)
{
var a = kv.Key; // false error CS0170: Use of possibly unassigned field
}
}
public static void Test5(IEnumerable<((int, int), string)> en)
{
foreach (((int, int k) t, string s) in en)
{
var a = t.k; // false error CS0170: Use of possibly unassigned field
System.Console.WriteLine(a);
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "0");
}
[Fact]
[WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")]
public void DefAssignmentsStruct002()
{
string source = @"
public class MyClass
{
public static void Main()
{
var data = new int[10];
var arr = new int[2];
foreach (arr[out int size] in data) {}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (9,36): error CS0230: Type and identifier are both required in a foreach statement
// foreach (arr[out int size] in data) {}
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(9, 36)
);
}
[Fact]
[WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")]
public void DefAssignmentsStruct003()
{
string source = @"
public class MyClass
{
public static void Main()
{
var data = new (int, int)[10];
var arr = new int[2];
foreach ((arr[out int size], int b) in data) {}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (9,27): error CS1615: Argument 1 may not be passed with the 'out' keyword
// foreach ((arr[out int size], int b) in data) {}
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int size").WithArguments("1", "out").WithLocation(9, 27),
// (9,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((arr[out int size], int b) in data) {}
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(arr[out int size], int b)").WithLocation(9, 18)
);
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_01()
{
string source = @"
class C
{
static event System.Action E;
static void Main()
{
(E, _) = (null, 1);
System.Console.WriteLine(E == null);
(E, _) = (Handler, 1);
E();
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput:
@"True
Handler");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_02()
{
string source = @"
struct S
{
event System.Action E;
class C
{
static void Main()
{
var s = new S();
(s.E, _) = (null, 1);
System.Console.WriteLine(s.E == null);
(s.E, _) = (Handler, 1);
s.E();
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
}
";
var comp = CompileAndVerify(source, expectedOutput:
@"True
Handler");
comp.VerifyDiagnostics();
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_03()
{
string source1 = @"
public interface EventInterface
{
event System.Action E;
}
";
var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular);
string source2 = @"
class C : EventInterface
{
public event System.Action E;
static void Main()
{
var c = new C();
c.Test();
}
void Test()
{
(E, _) = (null, 1);
System.Console.WriteLine(E == null);
(E, _) = (Handler, 1);
E();
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
";
var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput:
@"True
Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() }));
comp2.VerifyDiagnostics();
Assert.True(comp2.Compilation.GetMember<IEventSymbol>("C.E").IsWindowsRuntimeEvent);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_04()
{
string source1 = @"
public interface EventInterface
{
event System.Action E;
}
";
var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular);
string source2 = @"
struct S : EventInterface
{
public event System.Action E;
class C
{
S s = new S();
static void Main()
{
var c = new C();
(GetC(c).s.E, _) = (null, GetInt(1));
System.Console.WriteLine(c.s.E == null);
(GetC(c).s.E, _) = (Handler, GetInt(2));
c.s.E();
}
static int GetInt(int i)
{
System.Console.WriteLine(i);
return i;
}
static C GetC(C c)
{
System.Console.WriteLine(""GetC"");
return c;
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
}
";
var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput:
@"GetC
1
True
GetC
2
Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() }));
comp2.VerifyDiagnostics();
Assert.True(comp2.Compilation.GetMember<IEventSymbol>("S.E").IsWindowsRuntimeEvent);
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_05()
{
string source = @"
class C
{
public static event System.Action E;
}
class Program
{
static void Main()
{
(C.E, _) = (null, 1);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (11,12): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C')
// (C.E, _) = (null, 1);
Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 12)
);
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_06()
{
string source = @"
class C
{
static event System.Action E
{
add {}
remove {}
}
static void Main()
{
(E, _) = (null, 1);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (12,10): error CS0079: The event 'C.E' can only appear on the left hand side of += or -=
// (E, _) = (null, 1);
Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "E").WithArguments("C.E").WithLocation(12, 10)
);
}
[Fact]
public void SimpleAssignInConstructor()
{
string source = @"
public class C
{
public long x;
public string y;
public C(int a, string b) => (x, y) = (a, b);
public static void Main()
{
var c = new C(1, ""hello"");
System.Console.WriteLine(c.x + "" "" + c.y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C..ctor(int, string)", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (long V_0,
string V_1)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.1
IL_0007: conv.i8
IL_0008: stloc.0
IL_0009: ldarg.2
IL_000a: stloc.1
IL_000b: ldarg.0
IL_000c: ldloc.0
IL_000d: stfld ""long C.x""
IL_0012: ldarg.0
IL_0013: ldloc.1
IL_0014: stfld ""string C.y""
IL_0019: ret
}");
}
[Fact]
public void DeconstructAssignInConstructor()
{
string source = @"
public class C
{
public long x;
public string y;
public C(C oldC) => (x, y) = oldC;
public C() { }
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
public static void Main()
{
var oldC = new C() { x = 1, y = ""hello"" };
var newC = new C(oldC);
System.Console.WriteLine(newC.x + "" "" + newC.y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C..ctor(C)", @"
{
// Code size 34 (0x22)
.maxstack 3
.locals init (int V_0,
string V_1,
long V_2)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.1
IL_0007: ldloca.s V_0
IL_0009: ldloca.s V_1
IL_000b: callvirt ""void C.Deconstruct(out int, out string)""
IL_0010: ldloc.0
IL_0011: conv.i8
IL_0012: stloc.2
IL_0013: ldarg.0
IL_0014: ldloc.2
IL_0015: stfld ""long C.x""
IL_001a: ldarg.0
IL_001b: ldloc.1
IL_001c: stfld ""string C.y""
IL_0021: ret
}");
}
[Fact]
public void AssignInConstructorWithProperties()
{
string source = @"
public class C
{
public long X { get; set; }
public string Y { get; }
private int z;
public ref int Z { get { return ref z; } }
public C(int a, string b, ref int c) => (X, Y, Z) = (a, b, c);
public static void Main()
{
int number = 2;
var c = new C(1, ""hello"", ref number);
System.Console.WriteLine($""{c.X} {c.Y} {c.Z}"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello 2");
comp.VerifyDiagnostics();
comp.VerifyIL("C..ctor(int, string, ref int)", @"
{
// Code size 39 (0x27)
.maxstack 4
.locals init (long V_0,
string V_1,
int V_2,
long V_3)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: call ""ref int C.Z.get""
IL_000c: ldarg.1
IL_000d: conv.i8
IL_000e: stloc.0
IL_000f: ldarg.2
IL_0010: stloc.1
IL_0011: ldarg.3
IL_0012: ldind.i4
IL_0013: stloc.2
IL_0014: ldarg.0
IL_0015: ldloc.0
IL_0016: dup
IL_0017: stloc.3
IL_0018: call ""void C.X.set""
IL_001d: ldarg.0
IL_001e: ldloc.1
IL_001f: stfld ""string C.<Y>k__BackingField""
IL_0024: ldloc.2
IL_0025: stind.i4
IL_0026: ret
}");
}
[Fact]
public void VerifyDeconstructionInAsync()
{
var source =
@"
using System.Threading.Tasks;
class C
{
static void Main()
{
System.Console.Write(C.M().Result);
}
static async Task<int> M()
{
await Task.Delay(0);
var (x, y) = (1, 2);
return x + y;
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "3");
}
[Fact]
public void DeconstructionWarnsForSelfAssignment()
{
var source =
@"
class C
{
object x = 1;
static object y = 2;
void M()
{
((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,11): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// ((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 11),
// (8,18): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// ((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "this.x").WithLocation(8, 18),
// (8,26): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// ((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "C.y").WithLocation(8, 26)
);
}
[Fact]
public void DeconstructionWarnsForSelfAssignment2()
{
var source =
@"
class C
{
object x = 1;
static object y = 2;
void M()
{
object z = 3;
(x, (y, z)) = (x, (y, z));
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, (y, z));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x"),
// (9,14): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, (y, z));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y").WithLocation(9, 14),
// (9,17): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, (y, z));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "z").WithLocation(9, 17)
);
}
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithUserDefinedConversionOnElement()
{
var source =
@"
class C
{
object x = 1;
static C y = null;
void M()
{
(x, y) = (x, (C)(D)y);
}
public static implicit operator C(D d) => null;
}
class D
{
public static implicit operator D(C c) => null;
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,10): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, y) = (x, (C)(D)y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 10)
);
}
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithNestedConversions()
{
var source =
@"
class C
{
object x = 1;
int y = 2;
byte b = 3;
void M()
{
// The conversions on the right-hand-side:
// - a deconstruction conversion
// - an implicit tuple literal conversion on the entire right-hand-side
// - another implicit tuple literal conversion on the nested tuple
// - a conversion on element `b`
(_, (x, y)) = (1, (x, b));
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (14,14): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (_, (x, y)) = (1, (x, b));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(14, 14)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithExplicitTupleConversion()
{
var source =
@"
class C
{
int y = 2;
byte b = 3;
void M()
{
// The conversions on the right-hand-side:
// - a deconstruction conversion on the entire right-hand-side
// - an identity conversion as its operand
// - an explicit tuple literal conversion as its operand
(y, _) = ((int, int))(y, b);
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
);
var tree = comp.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
Assert.Equal("((int, int))(y, b)", node.ToString());
comp.VerifyOperationTree(node, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(y, b)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 b)) (Syntax: '(y, b)')
NaturalType: (System.Int32 y, System.Byte b)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.Int32 C.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'y')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.Byte C.b (OperationKind.FieldReference, Type: System.Byte) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b')
");
}
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithDeconstruct()
{
var source =
@"
class C
{
object x = 1;
static object y = 2;
void M()
{
object z = 3;
(x, (y, z)) = (x, y);
}
}
static class Extensions
{
public static void Deconstruct(this object input, out object output1, out object output2)
{
output1 = input;
output2 = input;
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(9, 10)
);
}
[Fact]
public void TestDeconstructOnErrorType()
{
var source =
@"
class C
{
Error M()
{
int x, y;
(x, y) = M();
throw null;
}
}";
var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); // no ValueTuple reference
comp.VerifyDiagnostics(
// (4,5): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// Error M()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 5)
);
}
[Fact]
public void TestDeconstructOnErrorTypeFromImageReference()
{
var missing_cs = "public class Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = "public class C { public Missing M() { throw null; } }";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll);
var source =
@"
class D
{
void M()
{
int x, y;
(x, y) = new C().M();
throw null;
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.DebugDll); // no ValueTuple reference
comp.VerifyDiagnostics(
// (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// (x, y) = new C().M();
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18)
);
}
[Fact]
public void TestDeconstructOnErrorTypeFromCompilationReference()
{
var missing_cs = "public class Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = "public class C { public Missing M() { throw null; } }";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.ToMetadataReference() }, options: TestOptions.DebugDll);
var source =
@"
class D
{
void M()
{
int x, y;
(x, y) = new C().M();
throw null;
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.ToMetadataReference() }, options: TestOptions.DebugDll); // no ValueTuple reference
comp.VerifyDiagnostics(
// (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// (x, y) = new C().M();
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18)
);
}
[Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")]
public void TestDiscardedAssignmentNotLvalue()
{
var source = @"
class Program
{
struct S1
{
public int field;
public int Increment() => field++;
}
static void Main()
{
S1 v = default(S1);
v.Increment();
(_ = v).Increment();
System.Console.WriteLine(v.field);
}
}
";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction()
{
var source = @"
class C
{
static void Main()
{
var t = (1, 2);
var (a, b) = ((byte, byte))t;
System.Console.Write($""{a} {b}"");
}
}";
CompileAndVerify(source, expectedOutput: @"1 2");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction2()
{
var source = @"
class C
{
static void Main()
{
var t = (new C(), new D());
var (a, _) = ((byte, byte))t;
System.Console.Write($""{a}"");
}
public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; }
}
class D
{
public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; }
}";
CompileAndVerify(source, expectedOutput: @"Convert Convert2 1");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction3()
{
var source = @"
class C
{
static int A { set { System.Console.Write(""A ""); } }
static int B { set { System.Console.Write(""B""); } }
static void Main()
{
(A, B) = ((byte, byte))(new C(), new D());
}
public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; }
public C() { System.Console.Write(""C ""); }
}
class D
{
public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; }
public D() { System.Console.Write(""D ""); }
}";
var compilation = CompileAndVerify(source, expectedOutput: @"C Convert D Convert2 A B").Compilation;
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
Assert.Equal("((byte, byte))(new C(), new D())", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.Byte)) (Syntax: '((byte, byt ... ), new D())')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Byte, System.Byte)) (Syntax: '(new C(), new D())')
NaturalType: (C, D)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new C()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte C.op_Explicit(C c))
Operand:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte D.op_Explicit(D c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new D()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte D.op_Explicit(D c))
Operand:
IObjectCreationOperation (Constructor: D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'new D()')
Arguments(0)
Initializer:
null
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction4()
{
var source = @"
class C
{
static void Main()
{
var (a, _) = ((short, short))((int, int))(1L, 2L);
System.Console.Write($""{a}"");
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"1").Compilation;
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ElementAt(1);
Assert.Equal("((int, int))(1L, 2L)", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L')
");
Assert.Equal("((short, short))((int, int))(1L, 2L)", node.Parent.ToString());
compilation.VerifyOperationTree(node.Parent, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int16, System.Int16)) (Syntax: '((short, sh ... t))(1L, 2L)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L')
");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void UserDefinedCastInDeconstruction()
{
var source = @"
class C
{
static void Main()
{
var c = new C();
var (a, b) = ((byte, byte))c;
System.Console.Write($""{a} {b}"");
}
public static explicit operator (byte, byte)(C c)
{
return (3, 4);
}
}";
CompileAndVerify(source, expectedOutput: @"3 4");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void DeconstructionLoweredToNothing()
{
var source = @"
class C
{
static void M()
{
for (var(_, _) = (1, 2); ; (_, _) = (3, 4))
{
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("C.M", @"
{
// Code size 2 (0x2)
.maxstack 0
IL_0000: br.s IL_0000
}");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void DeconstructionLoweredToNothing2()
{
var source = @"
class C
{
static void M()
{
(_, _) = (1, 2);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("C.M", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void DeconstructionLoweredToNothing3()
{
var source = @"
class C
{
static void Main()
{
foreach (var(_, _) in new[] { (1, 2) })
{
System.Console.Write(""once"");
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "once");
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName()
{
var source =
@"class C
{
static void Main()
{
int x = 0, y = 1;
var t = (x, y);
var (a, b) = t;
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ConditionalOperator()
{
var source =
@"class C
{
static void M(int a, int b, bool c)
{
(var x, var y) = c ? (a, default(object)) : (b, null);
(x, y) = c ? (a, default(string)) : (b, default(object));
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ImplicitArray()
{
var source =
@"class C
{
static void M(int x)
{
int y;
object z;
(y, z) = (new [] { (x, default(object)), (2, 3) })[0];
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")]
public void InferredName_Lambda()
{
// See https://github.com/dotnet/roslyn/issues/32006
// need to relax assertion in GetImplicitTupleLiteralConversion
var source =
@"class C
{
static T F<T>(System.Func<object, bool, T> f)
{
return f(null, false);
}
static void M()
{
var (x, y) = F((a, b) =>
{
if (b) return (default(object), a);
return (null, null);
});
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ConditionalOperator_LongTuple()
{
var source =
@"class C
{
static void M(object a, object b, bool c)
{
var (_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) = c ?
(1, 2, 3, 4, 5, 6, 7, a, b, 10) :
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ConditionalOperator_UseSite()
{
var source =
@"class C
{
static void M(int a, int b, bool c)
{
var (x, y) = c ? ((object)1, a) : (b, 2);
}
}
namespace System
{
struct ValueTuple<T1, T2>
{
public T1 Item1;
private T2 Item2;
public ValueTuple(T1 item1, T2 item2) => throw null;
}
}";
var expected = new[] {
// (12,19): warning CS0649: Field '(T1, T2).Item1' is never assigned to, and will always have its default value
// public T1 Item1;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item1").WithArguments("(T1, T2).Item1", "").WithLocation(12, 19),
// (13,20): warning CS0169: The field '(T1, T2).Item2' is never used
// private T2 Item2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20)
};
// C# 7.0
var comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics(expected);
// C# 7.1
comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics(expected);
}
[Fact]
public void InferredName_ConditionalOperator_UseSite_AccessingWithinConstructor()
{
var source =
@"class C
{
static void M(int a, int b, bool c)
{
var (x, y) = c ? ((object)1, a) : (b, 2);
}
}
namespace System
{
struct ValueTuple<T1, T2>
{
public T1 Item1;
private T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
}
}";
var expected = new[]
{
// (13,20): warning CS0169: The field '(T1, T2).Item2' is never used
// private T2 Item2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20),
// (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller
// public ValueTuple(T1 item1, T2 item2)
Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16),
// (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller
// public ValueTuple(T1 item1, T2 item2)
Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16),
// (17,13): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2'
// Item2 = item2;
Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(17, 13)
};
// C# 7.0
var comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics(expected);
// C# 7.1
comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics(expected);
}
[Fact]
public void TestGetDeconstructionInfoOnIncompleteCode()
{
string source = @"
class C
{
void M() { var (y1, y2) =}
void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; }
}
";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First();
Assert.Equal("var (y1, y2) =", node.ToString());
var info = model.GetDeconstructionInfo(node);
Assert.Null(info.Method);
Assert.Empty(info.Nested);
}
[Fact]
public void TestDeconstructStructThis()
{
string source = @"
public struct S
{
int I;
public static void Main()
{
S s = new S();
s.M();
}
public void M()
{
this.I = 42;
var (x, (y, z)) = (this, this /* mutating deconstruction */);
System.Console.Write($""{x.I} {y} {z}"");
}
void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "42 42 43");
}
[Fact]
public void TestDeconstructClassThis()
{
string source = @"
public class C
{
int I;
public static void Main()
{
C c = new C();
c.M();
}
public void M()
{
this.I = 42;
var (x, (y, z)) = (this, this /* mutating deconstruction */);
System.Console.Write($""{x.I} {y} {z}"");
}
void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "44 42 43");
}
[Fact]
public void AssigningConditional_OutParams()
{
string source = @"
using System;
class C
{
static void Main()
{
Test(true, false);
Test(false, true);
Test(false, false);
}
static void Test(bool b1, bool b2)
{
M(out int x, out int y, b1, b2);
Console.Write(x);
Console.Write(y);
}
static void M(out int x, out int y, bool b1, bool b2)
{
(x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060");
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.2
IL_0001: brtrue.s IL_0018
IL_0003: ldarg.3
IL_0004: brtrue.s IL_000f
IL_0006: ldarg.0
IL_0007: ldc.i4.s 50
IL_0009: stind.i4
IL_000a: ldarg.1
IL_000b: ldc.i4.s 60
IL_000d: stind.i4
IL_000e: ret
IL_000f: ldarg.0
IL_0010: ldc.i4.s 30
IL_0012: stind.i4
IL_0013: ldarg.1
IL_0014: ldc.i4.s 40
IL_0016: stind.i4
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.s 10
IL_001b: stind.i4
IL_001c: ldarg.1
IL_001d: ldc.i4.s 20
IL_001f: stind.i4
IL_0020: ret
}");
}
[Fact]
public void AssigningConditional_VarDeconstruction()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
}
static void M(bool b1, bool b2)
{
var (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
Console.Write(x);
Console.Write(y);
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060");
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0016
IL_0003: ldarg.1
IL_0004: brtrue.s IL_000e
IL_0006: ldc.i4.s 50
IL_0008: stloc.0
IL_0009: ldc.i4.s 60
IL_000b: stloc.1
IL_000c: br.s IL_001c
IL_000e: ldc.i4.s 30
IL_0010: stloc.0
IL_0011: ldc.i4.s 40
IL_0013: stloc.1
IL_0014: br.s IL_001c
IL_0016: ldc.i4.s 10
IL_0018: stloc.0
IL_0019: ldc.i4.s 20
IL_001b: stloc.1
IL_001c: ldloc.0
IL_001d: call ""void System.Console.Write(int)""
IL_0022: ldloc.1
IL_0023: call ""void System.Console.Write(int)""
IL_0028: ret
}");
}
[Fact]
public void AssigningConditional_MixedDeconstruction()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
}
static void M(bool b1, bool b2)
{
(var x, long y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
Console.Write(x);
Console.Write(y);
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060");
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 50 (0x32)
.maxstack 1
.locals init (int V_0, //x
long V_1, //y
long V_2)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_001c
IL_0003: ldarg.1
IL_0004: brtrue.s IL_0011
IL_0006: ldc.i4.s 60
IL_0008: conv.i8
IL_0009: stloc.2
IL_000a: ldc.i4.s 50
IL_000c: stloc.0
IL_000d: ldloc.2
IL_000e: stloc.1
IL_000f: br.s IL_0025
IL_0011: ldc.i4.s 40
IL_0013: conv.i8
IL_0014: stloc.2
IL_0015: ldc.i4.s 30
IL_0017: stloc.0
IL_0018: ldloc.2
IL_0019: stloc.1
IL_001a: br.s IL_0025
IL_001c: ldc.i4.s 20
IL_001e: conv.i8
IL_001f: stloc.2
IL_0020: ldc.i4.s 10
IL_0022: stloc.0
IL_0023: ldloc.2
IL_0024: stloc.1
IL_0025: ldloc.0
IL_0026: call ""void System.Console.Write(int)""
IL_002b: ldloc.1
IL_002c: call ""void System.Console.Write(long)""
IL_0031: ret
}");
}
[Fact]
public void AssigningConditional_SideEffects()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
SideEffect(true);
SideEffect(false);
}
static int left;
static int right;
static ref int SideEffect(bool isLeft)
{
Console.WriteLine($""{(isLeft ? ""left"" : ""right"")}: {(isLeft ? left : right)}"");
return ref isLeft ? ref left : ref right;
}
static void M(bool b1, bool b2)
{
(SideEffect(isLeft: true), SideEffect(isLeft: false)) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
}
}
";
var expected =
@"left: 0
right: 0
left: 10
right: 20
left: 30
right: 40
left: 50
right: 60";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected);
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (int& V_0,
int& V_1)
IL_0000: ldc.i4.1
IL_0001: call ""ref int C.SideEffect(bool)""
IL_0006: stloc.0
IL_0007: ldc.i4.0
IL_0008: call ""ref int C.SideEffect(bool)""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0026
IL_0011: ldarg.1
IL_0012: brtrue.s IL_001d
IL_0014: ldloc.0
IL_0015: ldc.i4.s 50
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: ldc.i4.s 60
IL_001b: stind.i4
IL_001c: ret
IL_001d: ldloc.0
IL_001e: ldc.i4.s 30
IL_0020: stind.i4
IL_0021: ldloc.1
IL_0022: ldc.i4.s 40
IL_0024: stind.i4
IL_0025: ret
IL_0026: ldloc.0
IL_0027: ldc.i4.s 10
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: ldc.i4.s 20
IL_002d: stind.i4
IL_002e: ret
}");
}
[Fact]
public void AssigningConditional_SideEffects_RHS()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
}
static T Echo<T>(T v, int i)
{
Console.WriteLine(i + "": "" + v);
return v;
}
static void M(bool b1, bool b2)
{
var (x, y) = Echo(b1, 1) ? Echo((10, 20), 2) : Echo(b2, 3) ? Echo((30, 40), 4) : Echo((50, 60), 5);
Console.WriteLine(""x: "" + x);
Console.WriteLine(""y: "" + y);
Console.WriteLine();
}
}
";
var expectedOutput =
@"1: True
2: (10, 20)
x: 10
y: 20
1: False
3: True
4: (30, 40)
x: 30
y: 40
1: False
3: False
5: (50, 60)
x: 50
y: 60
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningConditional_UnusedDeconstruction()
{
string source = @"
class C
{
static void M(bool b1, bool b2)
{
(_, _) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldarg.1
IL_0004: pop
IL_0005: ret
}");
}
[Fact, WorkItem(46562, "https://github.com/dotnet/roslyn/issues/46562")]
public void CompoundAssignment()
{
string source = @"
class C
{
void M()
{
decimal x = 0;
(var y, _) += 0.00m;
(int z, _) += z;
(var t, _) += (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (6,17): warning CS0219: The variable 'x' is assigned but its value is never used
// decimal x = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17),
// (7,10): error CS8185: A declaration is not allowed in this context.
// (var y, _) += 0.00m;
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var y").WithLocation(7, 10),
// (7,17): error CS0103: The name '_' does not exist in the current context
// (var y, _) += 0.00m;
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 17),
// (8,10): error CS8185: A declaration is not allowed in this context.
// (int z, _) += z;
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z").WithLocation(8, 10),
// (8,10): error CS0165: Use of unassigned local variable 'z'
// (int z, _) += z;
Diagnostic(ErrorCode.ERR_UseDefViolation, "int z").WithArguments("z").WithLocation(8, 10),
// (8,17): error CS0103: The name '_' does not exist in the current context
// (int z, _) += z;
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 17),
// (9,10): error CS8185: A declaration is not allowed in this context.
// (var t, _) += (1, 2);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var t").WithLocation(9, 10),
// (9,17): error CS0103: The name '_' does not exist in the current context
// (var t, _) += (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 17)
);
}
[Fact, WorkItem(50654, "https://github.com/dotnet/roslyn/issues/50654")]
public void Repro50654()
{
string source = @"
class C
{
static void Main()
{
(int, (int, (int, int), (int, int)))[] vals = new[]
{
(1, (2, (3, 4), (5, 6))),
(11, (12, (13, 14), (15, 16)))
};
foreach (var (a, (b, (c, d), (e, f))) in vals)
{
System.Console.Write($""{a + b + c + d + e + f} "");
}
foreach ((int a, (int b, (int c, int d), (int e, int f))) in vals)
{
System.Console.Write($""{a + b + c + d + e + f} "");
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "21 81 21 81");
}
[Fact]
public void MixDeclarationAndAssignmentPermutationsOf2()
{
string source = @"
class C
{
static void Main()
{
int x1 = 0;
(x1, string y1) = new C();
System.Console.WriteLine(x1 + "" "" + y1);
int x2;
(x2, var y2) = new C();
System.Console.WriteLine(x2 + "" "" + y2);
string y3 = """";
(int x3, y3) = new C();
System.Console.WriteLine(x3 + "" "" + y3);
string y4;
(var x4, y4) = new C();
System.Console.WriteLine(x4 + "" "" + y4);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello
1 hello
1 hello
1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 188 (0xbc)
.maxstack 3
.locals init (int V_0, //x1
string V_1, //y1
int V_2, //x2
string V_3, //y2
string V_4, //y3
int V_5, //x3
string V_6, //y4
int V_7, //x4
int V_8,
string V_9)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: newobj ""C..ctor()""
IL_0007: ldloca.s V_8
IL_0009: ldloca.s V_9
IL_000b: callvirt ""void C.Deconstruct(out int, out string)""
IL_0010: ldloc.s V_8
IL_0012: stloc.0
IL_0013: ldloc.s V_9
IL_0015: stloc.1
IL_0016: ldloca.s V_0
IL_0018: call ""string int.ToString()""
IL_001d: ldstr "" ""
IL_0022: ldloc.1
IL_0023: call ""string string.Concat(string, string, string)""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: newobj ""C..ctor()""
IL_0032: ldloca.s V_8
IL_0034: ldloca.s V_9
IL_0036: callvirt ""void C.Deconstruct(out int, out string)""
IL_003b: ldloc.s V_8
IL_003d: stloc.2
IL_003e: ldloc.s V_9
IL_0040: stloc.3
IL_0041: ldloca.s V_2
IL_0043: call ""string int.ToString()""
IL_0048: ldstr "" ""
IL_004d: ldloc.3
IL_004e: call ""string string.Concat(string, string, string)""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ldstr """"
IL_005d: stloc.s V_4
IL_005f: newobj ""C..ctor()""
IL_0064: ldloca.s V_8
IL_0066: ldloca.s V_9
IL_0068: callvirt ""void C.Deconstruct(out int, out string)""
IL_006d: ldloc.s V_8
IL_006f: stloc.s V_5
IL_0071: ldloc.s V_9
IL_0073: stloc.s V_4
IL_0075: ldloca.s V_5
IL_0077: call ""string int.ToString()""
IL_007c: ldstr "" ""
IL_0081: ldloc.s V_4
IL_0083: call ""string string.Concat(string, string, string)""
IL_0088: call ""void System.Console.WriteLine(string)""
IL_008d: newobj ""C..ctor()""
IL_0092: ldloca.s V_8
IL_0094: ldloca.s V_9
IL_0096: callvirt ""void C.Deconstruct(out int, out string)""
IL_009b: ldloc.s V_8
IL_009d: stloc.s V_7
IL_009f: ldloc.s V_9
IL_00a1: stloc.s V_6
IL_00a3: ldloca.s V_7
IL_00a5: call ""string int.ToString()""
IL_00aa: ldstr "" ""
IL_00af: ldloc.s V_6
IL_00b1: call ""string string.Concat(string, string, string)""
IL_00b6: call ""void System.Console.WriteLine(string)""
IL_00bb: ret
}");
}
[Fact]
public void MixDeclarationAndAssignmentPermutationsOf3()
{
string source = @"
class C
{
static void Main()
{
int x1;
string y1;
(x1, y1, var z1) = new C();
System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1);
int x2;
bool z2;
(x2, var y2, z2) = new C();
System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2);
string y3;
bool z3;
(var x3, y3, z3) = new C();
System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3);
bool z4;
(var x4, var y4, z4) = new C();
System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4);
string y5;
(var x5, y5, var z5) = new C();
System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5);
int x6;
(x6, var y6, var z6) = new C();
System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6);
}
public void Deconstruct(out int a, out string b, out bool c)
{
a = 1;
b = ""hello"";
c = true;
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True
1 hello True
1 hello True
1 hello True
1 hello True
1 hello True");
comp.VerifyDiagnostics();
}
[Fact]
public void DontAllowMixedDeclarationAndAssignmentInExpressionContext()
{
string source = @"
class C
{
static void Main()
{
int x1 = 0;
var z1 = (x1, string y1) = new C();
string y2 = """";
var z2 = (int x2, y2) = new C();
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,23): error CS8185: A declaration is not allowed in this context.
// var z1 = (x1, string y1) = new C();
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string y1").WithLocation(7, 23),
// (9,19): error CS8185: A declaration is not allowed in this context.
// var z2 = (int x2, y2) = new C();
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(9, 19));
}
[Fact]
public void DontAllowMixedDeclarationAndAssignmentInForeachDeclarationVariable()
{
string source = @"
class C
{
static void Main()
{
int x1;
foreach((x1, string y1) in new C[0]);
string y2;
foreach((int x2, y2) in new C[0]);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (6,13): warning CS0168: The variable 'x1' is declared but never used
// int x1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(6, 13),
// (7,17): error CS8186: A foreach loop must declare its iteration variables.
// foreach((x1, string y1) in new C[0]);
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(x1, string y1)").WithLocation(7, 17),
// (8,16): warning CS0168: The variable 'y2' is declared but never used
// string y2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "y2").WithArguments("y2").WithLocation(8, 16),
// (9,17): error CS8186: A foreach loop must declare its iteration variables.
// foreach((int x2, y2) in new C[0]);
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int x2, y2)").WithLocation(9, 17));
}
[Fact]
public void DuplicateDeclarationOfVariableDeclaredInMixedDeclarationAndAssignment()
{
string source = @"
class C
{
static void Main()
{
int x1;
string y1;
(x1, string y1) = new C();
string y2;
(int x2, y2) = new C();
int x2;
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(
// (7,16): warning CS0168: The variable 'y1' is declared but never used
// string y1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "y1").WithArguments("y1").WithLocation(7, 16),
// (8,21): error CS0128: A local variable or function named 'y1' is already defined in this scope
// (x1, string y1) = new C();
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(8, 21),
// (11,13): error CS0128: A local variable or function named 'x2' is already defined in this scope
// int x2;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(11, 13),
// (11,13): warning CS0168: The variable 'x2' is declared but never used
// int x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(11, 13));
}
[Fact]
public void AssignmentToUndeclaredVariableInMixedDeclarationAndAssignment()
{
string source = @"
class C
{
static void Main()
{
(x1, string y1) = new C();
(int x2, y2) = new C();
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(
// (6,10): error CS0103: The name 'x1' does not exist in the current context
// (x1, string y1) = new C();
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 10),
// (7,18): error CS0103: The name 'y2' does not exist in the current context
// (int x2, y2) = new C();
Diagnostic(ErrorCode.ERR_NameNotInContext, "y2").WithArguments("y2").WithLocation(7, 18));
}
[Fact]
public void MixedDeclarationAndAssignmentInForInitialization()
{
string source = @"
class C
{
static void Main()
{
int x1;
for((x1, string y1) = new C(); x1 < 2; x1++)
System.Console.WriteLine(x1 + "" "" + y1);
string y2;
for((int x2, y2) = new C(); x2 < 2; x2++)
System.Console.WriteLine(x2 + "" "" + y2);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello
1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (int V_0, //x1
string V_1, //y2
string V_2, //y1
int V_3,
string V_4,
int V_5) //x2
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_3
IL_0007: ldloca.s V_4
IL_0009: callvirt ""void C.Deconstruct(out int, out string)""
IL_000e: ldloc.3
IL_000f: stloc.0
IL_0010: ldloc.s V_4
IL_0012: stloc.2
IL_0013: br.s IL_0030
IL_0015: ldloca.s V_0
IL_0017: call ""string int.ToString()""
IL_001c: ldstr "" ""
IL_0021: ldloc.2
IL_0022: call ""string string.Concat(string, string, string)""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: add
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: ldc.i4.2
IL_0032: blt.s IL_0015
IL_0034: newobj ""C..ctor()""
IL_0039: ldloca.s V_3
IL_003b: ldloca.s V_4
IL_003d: callvirt ""void C.Deconstruct(out int, out string)""
IL_0042: ldloc.3
IL_0043: stloc.s V_5
IL_0045: ldloc.s V_4
IL_0047: stloc.1
IL_0048: br.s IL_0067
IL_004a: ldloca.s V_5
IL_004c: call ""string int.ToString()""
IL_0051: ldstr "" ""
IL_0056: ldloc.1
IL_0057: call ""string string.Concat(string, string, string)""
IL_005c: call ""void System.Console.WriteLine(string)""
IL_0061: ldloc.s V_5
IL_0063: ldc.i4.1
IL_0064: add
IL_0065: stloc.s V_5
IL_0067: ldloc.s V_5
IL_0069: ldc.i4.2
IL_006a: blt.s IL_004a
IL_006c: ret
}");
}
[Fact]
public void MixDeclarationAndAssignmentInTupleDeconstructPermutationsOf2()
{
string source = @"
class C
{
static void Main()
{
int x1 = 0;
(x1, string y1) = (1, ""hello"");
System.Console.WriteLine(x1 + "" "" + y1);
int x2;
(x2, var y2) = (1, ""hello"");
System.Console.WriteLine(x2 + "" "" + y2);
string y3 = """";
(int x3, y3) = (1, ""hello"");
System.Console.WriteLine(x3 + "" "" + y3);
string y4;
(var x4, y4) = (1, ""hello"");
System.Console.WriteLine(x4 + "" "" + y4);
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello
1 hello
1 hello
1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 140 (0x8c)
.maxstack 3
.locals init (int V_0, //x1
string V_1, //y1
int V_2, //x2
string V_3, //y2
string V_4, //y3
int V_5, //x3
string V_6, //y4
int V_7) //x4
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: stloc.0
IL_0004: ldstr ""hello""
IL_0009: stloc.1
IL_000a: ldloca.s V_0
IL_000c: call ""string int.ToString()""
IL_0011: ldstr "" ""
IL_0016: ldloc.1
IL_0017: call ""string string.Concat(string, string, string)""
IL_001c: call ""void System.Console.WriteLine(string)""
IL_0021: ldc.i4.1
IL_0022: stloc.2
IL_0023: ldstr ""hello""
IL_0028: stloc.3
IL_0029: ldloca.s V_2
IL_002b: call ""string int.ToString()""
IL_0030: ldstr "" ""
IL_0035: ldloc.3
IL_0036: call ""string string.Concat(string, string, string)""
IL_003b: call ""void System.Console.WriteLine(string)""
IL_0040: ldstr """"
IL_0045: stloc.s V_4
IL_0047: ldc.i4.1
IL_0048: stloc.s V_5
IL_004a: ldstr ""hello""
IL_004f: stloc.s V_4
IL_0051: ldloca.s V_5
IL_0053: call ""string int.ToString()""
IL_0058: ldstr "" ""
IL_005d: ldloc.s V_4
IL_005f: call ""string string.Concat(string, string, string)""
IL_0064: call ""void System.Console.WriteLine(string)""
IL_0069: ldc.i4.1
IL_006a: stloc.s V_7
IL_006c: ldstr ""hello""
IL_0071: stloc.s V_6
IL_0073: ldloca.s V_7
IL_0075: call ""string int.ToString()""
IL_007a: ldstr "" ""
IL_007f: ldloc.s V_6
IL_0081: call ""string string.Concat(string, string, string)""
IL_0086: call ""void System.Console.WriteLine(string)""
IL_008b: ret
}");
}
[Fact]
public void MixedDeclarationAndAssignmentCSharpNine()
{
string source = @"
class Program
{
static void Main()
{
int x1;
(x1, string y1) = new A();
string y2;
(int x2, y2) = new A();
bool z3;
(int x3, (string y3, z3)) = new B();
int x4;
(x4, var (y4, z4)) = new B();
}
}
class A
{
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
class B
{
public void Deconstruct(out int a, out (string b, bool c) tuple)
{
a = 1;
tuple = (""hello"", true);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics(
// (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (x1, string y1) = new A();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x1, string y1) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9),
// (9,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (int x2, y2) = new A();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x2, y2) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(9, 9),
// (11,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (int x3, (string y3, z3)) = new B();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x3, (string y3, z3)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(11, 9),
// (13,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (x4, var (y4, z4)) = new B();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x4, var (y4, z4)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(13, 9));
}
[Fact]
public void NestedMixedDeclarationAndAssignmentPermutations()
{
string source = @"
class C
{
static void Main()
{
int x1;
string y1;
(x1, (y1, var z1)) = new C();
System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1);
int x2;
bool z2;
(x2, (var y2, z2)) = new C();
System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2);
string y3;
bool z3;
(var x3, (y3, z3)) = new C();
System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3);
bool z4;
(var x4, (var y4, z4)) = new C();
System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4);
string y5;
(var x5, (y5, var z5)) = new C();
System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5);
int x6;
(x6, (var y6, var z6)) = new C();
System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6);
int x7;
(x7, var (y7, z7)) = new C();
System.Console.WriteLine(x7 + "" "" + y7 + "" "" + z7);
}
public void Deconstruct(out int a, out (string a, bool b) b)
{
a = 1;
b = (""hello"", true);
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True
1 hello True
1 hello True
1 hello True
1 hello True
1 hello True
1 hello True");
comp.VerifyDiagnostics();
}
[Fact]
public void MixedDeclarationAndAssignmentUseBeforeDeclaration()
{
string source = @"
class Program
{
static void Main()
{
(x1, string y1) = new A();
int x1;
(int x2, y2) = new A();
string y2;
(int x3, (string y3, z3)) = new B();
bool z3;
(x4, var (y4, z4)) = new B();
int x4;
}
}
class A
{
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
class B
{
public void Deconstruct(out int a, out (string b, bool c) tuple)
{
a = 1;
tuple = (""hello"", true);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview)
.VerifyDiagnostics(
// (6,10): error CS0841: Cannot use local variable 'x1' before it is declared
// (x1, string y1) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1", isSuppressed: false).WithArguments("x1").WithLocation(6, 10),
// (8,18): error CS0841: Cannot use local variable 'y2' before it is declared
// (int x2, y2) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y2", isSuppressed: false).WithArguments("y2").WithLocation(8, 18),
// (10,30): error CS0841: Cannot use local variable 'z3' before it is declared
// (int x3, (string y3, z3)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z3", isSuppressed: false).WithArguments("z3").WithLocation(10, 30),
// (12,10): error CS0841: Cannot use local variable 'x4' before it is declared
// (x4, var (y4, z4)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4", isSuppressed: false).WithArguments("x4").WithLocation(12, 10));
}
[Fact]
public void MixedDeclarationAndAssignmentUseDeclaredVariableInAssignment()
{
string source = @"
class Program
{
static void Main()
{
(var x1, x1) = new A();
(x2, var x2) = new A();
(var x3, (var y3, x3)) = new B();
(x4, (var y4, var x4)) = new B();
}
}
class A
{
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
class B
{
public void Deconstruct(out int a, out (string b, bool c) tuple)
{
a = 1;
tuple = (""hello"", true);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview)
.VerifyDiagnostics(
// (6,18): error CS0841: Cannot use local variable 'x1' before it is declared
// (var x1, x1) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 18),
// (7,10): error CS0841: Cannot use local variable 'x2' before it is declared
// (x2, var x2) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(7, 10),
// (8,27): error CS0841: Cannot use local variable 'x3' before it is declared
// (var x3, (var y3, x3)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x3").WithArguments("x3").WithLocation(8, 27),
// (9,10): error CS0841: Cannot use local variable 'x4' before it is declared
// (x4, (var y4, var x4)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 10));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
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.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
[CompilerTrait(CompilerFeature.Tuples)]
public class CodeGenDeconstructTests : CSharpTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
const string commonSource =
@"public class Pair<T1, T2>
{
T1 item1;
T2 item2;
public Pair(T1 item1, T2 item2)
{
this.item1 = item1;
this.item2 = item2;
}
public void Deconstruct(out T1 item1, out T2 item2)
{
System.Console.WriteLine($""Deconstructing {ToString()}"");
item1 = this.item1;
item2 = this.item2;
}
public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; }
}
public static class Pair
{
public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); }
}
public class Integer
{
public int state;
public override string ToString() { return state.ToString(); }
public Integer(int i) { state = i; }
public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); }
}
public class LongInteger
{
long state;
public LongInteger(long l) { state = l; }
public override string ToString() { return state.ToString(); }
}";
[Fact]
public void SimpleAssign()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(x, y)", lhs.ToString());
Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int64 x, System.String y)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
var right = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
Assert.Equal(@"new C()", right.ToString());
Assert.Equal("C", model.GetTypeInfo(right).Type.ToTestDisplayString());
Assert.Equal("C", model.GetTypeInfo(right).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(right).Kind);
};
var comp = CompileAndVerifyWithMscorlib40(source, expectedOutput: "1 hello", references: s_valueTupleRefs, sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (long V_0, //x
string V_1, //y
int V_2,
string V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_2
IL_0007: ldloca.s V_3
IL_0009: callvirt ""void C.Deconstruct(out int, out string)""
IL_000e: ldloc.2
IL_000f: conv.i8
IL_0010: stloc.0
IL_0011: ldloc.3
IL_0012: stloc.1
IL_0013: ldloca.s V_0
IL_0015: call ""string long.ToString()""
IL_001a: ldstr "" ""
IL_001f: ldloc.1
IL_0020: call ""string string.Concat(string, string, string)""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
}");
}
[Fact]
public void ObsoleteDeconstructMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
foreach (var (z1, z2) in new[] { new C() }) { }
}
[System.Obsolete]
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,18): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete
// (x, y) = new C();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 18),
// (10,34): warning CS0612: 'C.Deconstruct(out int, out string)' is obsolete
// foreach (var (z1, z2) in new[] { new C() }) { }
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new[] { new C() }").WithArguments("C.Deconstruct(out int, out string)").WithLocation(10, 34)
);
}
[Fact]
[WorkItem(13632, "https://github.com/dotnet/roslyn/issues/13632")]
public void SimpleAssignWithoutConversion()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (int V_0, //x
string V_1, //y
int V_2,
string V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_2
IL_0007: ldloca.s V_3
IL_0009: callvirt ""void C.Deconstruct(out int, out string)""
IL_000e: ldloc.2
IL_000f: stloc.0
IL_0010: ldloc.3
IL_0011: stloc.1
IL_0012: ldloca.s V_0
IL_0014: call ""string int.ToString()""
IL_0019: ldstr "" ""
IL_001e: ldloc.1
IL_001f: call ""string string.Concat(string, string, string)""
IL_0024: call ""void System.Console.WriteLine(string)""
IL_0029: ret
}");
}
[Fact]
public void DeconstructMethodAmbiguous()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
public void Deconstruct(out int a)
{
a = 2;
}
}";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree);
var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode();
Assert.Equal("(x, y) = new C()", deconstruction.ToString());
var deconstructionInfo = model.GetDeconstructionInfo(deconstruction);
var firstDeconstructMethod = ((CSharpCompilation)comp.Compilation).GetTypeByMetadataName("C").GetMembers(WellKnownMemberNames.DeconstructMethodName)
.OfType<SourceOrdinaryMethodSymbol>().Where(m => m.ParameterCount == 2).Single();
Assert.Equal(firstDeconstructMethod.GetPublicSymbol(), deconstructionInfo.Method);
Assert.Equal("void C.Deconstruct(out System.Int32 a, out System.String b)",
deconstructionInfo.Method.ToTestDisplayString());
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.ImplicitNumeric, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Null(nested[1].Method);
Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind);
Assert.Empty(nested[1].Nested);
var assignment = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression, occurrence: 2).AsNode();
Assert.Equal("a = 1", assignment.ToString());
var defaultInfo = model.GetDeconstructionInfo(assignment);
Assert.Null(defaultInfo.Method);
Assert.Empty(defaultInfo.Nested);
Assert.Equal(ConversionKind.UnsetConversionKind, defaultInfo.Conversion.Value.Kind);
}
[Fact]
[WorkItem(27520, "https://github.com/dotnet/roslyn/issues/27520")]
public void GetDeconstructionInfoOnIncompleteCode()
{
string source = @"
class C
{
static void M(string s)
{
foreach (char in s) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,18): error CS1525: Invalid expression term 'char'
// foreach (char in s) { }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "char").WithArguments("char").WithLocation(6, 18),
// (6,23): error CS0230: Type and identifier are both required in a foreach statement
// foreach (char in s) { }
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 23)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var foreachDeconstruction = (ForEachVariableStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode();
Assert.Equal(@"foreach (char in s) { }", foreachDeconstruction.ToString());
var deconstructionInfo = model.GetDeconstructionInfo(foreachDeconstruction);
Assert.Equal(Conversion.UnsetConversion, deconstructionInfo.Conversion);
Assert.Null(deconstructionInfo.Method);
Assert.Empty(deconstructionInfo.Nested);
}
[Fact]
[WorkItem(15634, "https://github.com/dotnet/roslyn/issues/15634")]
public void DeconstructMustReturnVoid()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
}
public int Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
return 42;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18)
);
}
[Fact]
public void VerifyExecutionOrder_Deconstruct()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForX().x, c.getHolderForY().y) = c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
getDeconstructReceiver
Deconstruct
Conversion1
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_Deconstruct_Conditional()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
bool b = true;
(c.getHolderForX().x, c.getHolderForY().y) = b ? c.getDeconstructReceiver() : default;
}
public void Deconstruct(out D1 x, out D2 y) { x = new D1(); y = new D2(); Console.WriteLine(""Deconstruct""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
getDeconstructReceiver
Deconstruct
Conversion1
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteral()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForX().x, c.getHolderForY().y) = (new D1(), new D2());
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
Constructor1
Conversion1
Constructor2
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteral_Conditional()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
static void Main()
{
C c = new C();
bool b = true;
(c.getHolderForX().x, c.getHolderForY().y) = b ? (new D1(), new D2()) : default;
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
";
string expected =
@"getHolderforX
getHolderforY
Constructor1
Constructor2
Conversion1
Conversion2
setX
setY
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteralAndDeconstruction()
{
string source = @"
using System;
class C
{
int w { set { Console.WriteLine($""setW""); } }
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = (new D1(), new D2(), new D3());
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); }
}
class D3
{
public D3() { Console.WriteLine(""Constructor3""); }
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforW
getHolderforY
getHolderforZ
getHolderforX
Constructor1
Conversion1
Constructor2
Constructor3
Conversion3
deconstruct
setW
setY
setZ
setX
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyExecutionOrder_TupleLiteralAndDeconstruction_Conditional()
{
string source = @"
using System;
class C
{
int w { set { Console.WriteLine($""setW""); } }
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForW() { Console.WriteLine(""getHolderforW""); return this; }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
static void Main()
{
C c = new C();
bool b = false;
(c.getHolderForW().w, (c.getHolderForY().y, c.getHolderForZ().z), c.getHolderForX().x) = b ? default : (new D1(), new D2(), new D3());
}
}
class D1
{
public D1() { Console.WriteLine(""Constructor1""); }
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public D2() { Console.WriteLine(""Constructor2""); }
public void Deconstruct(out int x, out int y) { x = 2; y = 3; Console.WriteLine(""deconstruct""); }
}
class D3
{
public D3() { Console.WriteLine(""Constructor3""); }
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforW
getHolderforY
getHolderforZ
getHolderforX
Constructor1
Constructor2
Constructor3
deconstruct
Conversion1
Conversion3
setW
setY
setZ
setX
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void DifferentVariableKinds()
{
string source = @"
class C
{
int[] ArrayIndexer = new int[1];
string property;
string Property { set { property = value; } }
string AutoProperty { get; set; }
static void Main()
{
C c = new C();
(c.ArrayIndexer[0], c.Property, c.AutoProperty) = new C();
System.Console.WriteLine(c.ArrayIndexer[0] + "" "" + c.property + "" "" + c.AutoProperty);
}
public void Deconstruct(out int a, out string b, out string c)
{
a = 1;
b = ""hello"";
c = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello world");
comp.VerifyDiagnostics();
}
[Fact]
public void Dynamic()
{
string source = @"
class C
{
dynamic Dynamic1;
dynamic Dynamic2;
static void Main()
{
C c = new C();
(c.Dynamic1, c.Dynamic2) = c;
System.Console.WriteLine(c.Dynamic1 + "" "" + c.Dynamic2);
}
public void Deconstruct(out int a, out dynamic b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructInterfaceOnStruct()
{
string source = @"
interface IDeconstructable
{
void Deconstruct(out int a, out string b);
}
struct C : IDeconstructable
{
string state;
static void Main()
{
int x;
string y;
IDeconstructable c = new C() { state = ""initial"" };
System.Console.Write(c);
(x, y) = c;
System.Console.WriteLine("" "" + c + "" "" + x + "" "" + y);
}
void IDeconstructable.Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
state = ""modified"";
}
public override string ToString() { return state; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "initial modified 1 hello", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructMethodHasParams2()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator
{
a = 1;
b = ""ignored"";
}
public void Deconstruct(out int a, out string b)
{
a = 2;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "2 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void OutParamsDisallowed()
{
string source = @"
class C
{
public void Deconstruct(out int a, out string b, out params int[] c)
{
a = 1;
b = ""ignored"";
c = new[] { 2, 2 };
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,58): error CS8328: The parameter modifier 'params' cannot be used with 'out'
// public void Deconstruct(out int a, out string b, out params int[] c)
Diagnostic(ErrorCode.ERR_BadParameterModifiers, "params").WithArguments("params", "out").WithLocation(4, 58));
}
[Fact]
public void DeconstructMethodHasArglist2()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator
{
a = 2;
b = ""ignored"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DifferentStaticVariableKinds()
{
string source = @"
class C
{
static int[] ArrayIndexer = new int[1];
static string property;
static string Property { set { property = value; } }
static string AutoProperty { get; set; }
static void Main()
{
(C.ArrayIndexer[0], C.Property, C.AutoProperty) = new C();
System.Console.WriteLine(C.ArrayIndexer[0] + "" "" + C.property + "" "" + C.AutoProperty);
}
public void Deconstruct(out int a, out string b, out string c)
{
a = 1;
b = ""hello"";
c = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello world");
comp.VerifyDiagnostics();
}
[Fact]
public void DifferentVariableRefKinds()
{
string source = @"
class C
{
static void Main()
{
long a = 1;
int b;
C.M(ref a, out b);
System.Console.WriteLine(a + "" "" + b);
}
static void M(ref long a, out int b)
{
(a, b) = new C();
}
public void Deconstruct(out int x, out byte y)
{
x = 2;
y = (byte)3;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "2 3");
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void RefReturningMethod()
{
string source = @"
class C
{
static int i = 0;
static void Main()
{
(M(), M()) = new C();
System.Console.WriteLine($""Final i is {i}"");
}
static ref int M()
{
System.Console.WriteLine($""M (previous i is {i})"");
return ref i;
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 42;
y = 43;
}
}
";
var expected =
@"M (previous i is 0)
M (previous i is 0)
Deconstruct
Final i is 43
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void RefReturningProperty()
{
string source = @"
class C
{
static int i = 0;
static void Main()
{
(P, P) = new C();
System.Console.WriteLine($""Final i is {i}"");
}
static ref int P
{
get
{
System.Console.WriteLine($""P (previous i is {i})"");
return ref i;
}
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 42;
y = 43;
}
}
";
var expected =
@"P (previous i is 0)
P (previous i is 0)
Deconstruct
Final i is 43
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void RefReturningMethodFlow()
{
string source = @"
struct C
{
static C i;
static C P { get { System.Console.WriteLine(""getP""); return i; } set { System.Console.WriteLine(""setP""); i = value; } }
static void Main()
{
(M(), M()) = P;
}
static ref C M()
{
System.Console.WriteLine($""M (previous i is {i})"");
return ref i;
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 42;
y = 43;
}
public static implicit operator C(int x)
{
System.Console.WriteLine(""conversion"");
return new C();
}
}
";
var expected =
@"M (previous i is C)
M (previous i is C)
getP
Deconstruct
conversion
conversion";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void Indexers()
{
string source = @"
class C
{
static SomeArray array;
static void Main()
{
int y;
(Goo()[Bar()], y) = new C();
System.Console.WriteLine($""Final array values[2] {array.values[2]}"");
}
static SomeArray Goo()
{
System.Console.WriteLine($""Goo"");
array = new SomeArray();
return array;
}
static int Bar()
{
System.Console.WriteLine($""Bar"");
return 2;
}
void Deconstruct(out int x, out int y)
{
System.Console.WriteLine(""Deconstruct"");
x = 101;
y = 102;
}
}
class SomeArray
{
public int[] values;
public SomeArray() { values = new [] { 42, 43, 44 }; }
public int this[int index] {
get { System.Console.WriteLine($""indexGet (with value {values[index]})""); return values[index]; }
set { System.Console.WriteLine($""indexSet (with value {value})""); values[index] = value; }
}
}
";
var expected =
@"Goo
Bar
Deconstruct
indexSet (with value 101)
Final array values[2] 101
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningTuple()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
int i = 1;
(x, y) = (i, ""hello"");
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree);
var deconstruction = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Single();
var deconstructionInfo = model.GetDeconstructionInfo(deconstruction);
Assert.Null(deconstructionInfo.Method);
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Null(nested[1].Method);
Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind);
Assert.Empty(nested[1].Nested);
var tuple = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(i, ""hello"")", tuple.ToString());
var tupleConversion = model.GetConversion(tuple);
Assert.Equal(ConversionKind.ImplicitTupleLiteral, tupleConversion.Kind);
Assert.Equal(ConversionKind.ImplicitNumeric, tupleConversion.UnderlyingConversions[0].Kind);
}
[Fact]
public void AssigningTupleWithConversion()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = M();
System.Console.WriteLine(x + "" "" + y);
}
static System.ValueTuple<int, string> M()
{
return (1, ""hello"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningLongTuple()
{
string source = @"
class C
{
static void Main()
{
long x;
int y;
(x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, 2);
System.Console.WriteLine(string.Concat(x, "" "", y));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "4 2");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0) //y
IL_0000: ldc.i4.4
IL_0001: conv.i8
IL_0002: ldc.i4.2
IL_0003: stloc.0
IL_0004: box ""long""
IL_0009: ldstr "" ""
IL_000e: ldloc.0
IL_000f: box ""int""
IL_0014: call ""string string.Concat(object, object, object)""
IL_0019: call ""void System.Console.WriteLine(string)""
IL_001e: ret
}");
}
[Fact]
public void AssigningLongTupleWithNames()
{
string source = @"
class C
{
static void Main()
{
long x;
int y;
(x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "9 10");
comp.VerifyDiagnostics(
// (9,43): warning CS8123: The tuple element name 'a' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "a: 1").WithArguments("a", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 43),
// (9,49): warning CS8123: The tuple element name 'b' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "b: 2").WithArguments("b", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 49),
// (9,55): warning CS8123: The tuple element name 'c' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "c: 3").WithArguments("c", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 55),
// (9,61): warning CS8123: The tuple element name 'd' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "d: 4").WithArguments("d", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 61),
// (9,67): warning CS8123: The tuple element name 'e' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "e: 5").WithArguments("e", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 67),
// (9,73): warning CS8123: The tuple element name 'f' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "f: 6").WithArguments("f", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 73),
// (9,79): warning CS8123: The tuple element name 'g' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "g: 7").WithArguments("g", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 79),
// (9,85): warning CS8123: The tuple element name 'h' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "h: 8").WithArguments("h", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 85),
// (9,91): warning CS8123: The tuple element name 'i' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "i: 9").WithArguments("i", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 91),
// (9,97): warning CS8123: The tuple element name 'j' is ignored because a different name is specified by the target type '(long, long, long, long, long, long, long, long, long, int)'.
// (x, x, x, x, x, x, x, x, x, y) = (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10);
Diagnostic(ErrorCode.WRN_TupleLiteralNameMismatch, "j: 10").WithArguments("j", "(long, long, long, long, long, long, long, long, long, int)").WithLocation(9, 97)
);
}
[Fact]
public void AssigningLongTuple2()
{
string source = @"
class C
{
static void Main()
{
long x;
int y;
(x, x, x, x, x, x, x, x, x, y) = (1, 1, 1, 1, 1, 1, 1, 1, 4, (byte)2);
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "4 2");
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningTypelessTuple()
{
string source = @"
class C
{
static void Main()
{
string x = ""goodbye"";
string y;
(x, y) = (null, ""hello"");
System.Console.WriteLine($""{x}{y}"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (string V_0) //y
IL_0000: ldnull
IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""string string.Concat(string, string)""
IL_000d: call ""void System.Console.WriteLine(string)""
IL_0012: ret
} ");
}
[Fact]
public void ValueTupleReturnIsNotEmittedIfUnused()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = new C();
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0,
int V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_0
IL_0007: ldloca.s V_1
IL_0009: callvirt ""void C.Deconstruct(out int, out int)""
IL_000e: ret
}");
}
[Fact]
public void ValueTupleReturnIsEmittedIfUsed()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
var z = ((x, y) = new C());
z.ToString();
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2);
Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString());
};
var comp = CompileAndVerify(source, sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 37 (0x25)
.maxstack 3
.locals init (System.ValueTuple<int, int> V_0, //z
int V_1,
int V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_1
IL_0007: ldloca.s V_2
IL_0009: callvirt ""void C.Deconstruct(out int, out int)""
IL_000e: ldloc.1
IL_000f: ldloc.2
IL_0010: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0015: stloc.0
IL_0016: ldloca.s V_0
IL_0018: constrained. ""System.ValueTuple<int, int>""
IL_001e: callvirt ""string object.ToString()""
IL_0023: pop
IL_0024: ret
}");
}
[Fact]
public void ValueTupleReturnIsEmittedIfUsed_WithCSharp7_1()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
var z = ((x, y) = new C());
z.ToString();
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var x = nodes.OfType<VariableDeclaratorSyntax>().ElementAt(2);
Assert.Equal("(System.Int32 x, System.Int32 y) z", model.GetDeclaredSymbol(x).ToTestDisplayString());
};
var comp = CompileAndVerify(source,
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleNotRequiredIfReturnIsNotUsed()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = new C();
System.Console.Write($""assignment: {x} {y}. "");
foreach (var (a, b) in new[] { new C() })
{
System.Console.Write($""foreach: {a} {b}."");
}
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "assignment: 1 2. foreach: 1 2.");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var xy = nodes.OfType<TupleExpressionSyntax>().Single();
Assert.Equal("(x, y)", xy.ToString());
var tuple1 = model.GetTypeInfo(xy).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tuple1.ToTestDisplayString());
var ab = nodes.OfType<DeclarationExpressionSyntax>().Single();
var tuple2 = model.GetTypeInfo(ab).Type;
Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", tuple2.ToTestDisplayString());
Assert.Equal("(System.Int32 a, System.Int32 b)[missing]", model.GetTypeInfo(ab).ConvertedType.ToTestDisplayString());
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleNotRequiredIfReturnIsNotUsed2()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
for((x, y) = new C(1); ; (x, y) = new C(2))
{
}
}
public C(int c) { }
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var tuple1 = nodes.OfType<TupleExpressionSyntax>().ElementAt(0);
Assert.Equal("(x, y) = new C(1)", tuple1.Parent.ToString());
var tupleType1 = model.GetTypeInfo(tuple1).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType1.ToTestDisplayString());
var tuple2 = nodes.OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal("(x, y) = new C(2)", tuple2.Parent.ToString());
var tupleType2 = model.GetTypeInfo(tuple1).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)[missing]", tupleType2.ToTestDisplayString());
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleNotRequiredIfReturnIsNotUsed3()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = new C();
}
public C() { }
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
namespace System
{
[Obsolete]
public struct ValueTuple<T1, T2>
{
[Obsolete]
public T1 Item1;
[Obsolete]
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; }
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyEmitDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var tuple = nodes.OfType<TupleExpressionSyntax>().ElementAt(0);
Assert.Equal("(x, y) = new C()", tuple.Parent.ToString());
var tupleType = model.GetTypeInfo(tuple).Type;
Assert.Equal("(System.Int32 x, System.Int32 y)", tupleType.ToTestDisplayString());
var underlying = ((INamedTypeSymbol)tupleType).TupleUnderlyingType;
Assert.Equal("(System.Int32, System.Int32)", underlying.ToTestDisplayString());
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleRequiredWhenRightHandSideIsTuple()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = (1, 2);
}
}
";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics(
// (7,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, 2)").WithArguments("System.ValueTuple`2").WithLocation(7, 18)
);
}
[Fact]
[WorkItem(18629, "https://github.com/dotnet/roslyn/issues/18629")]
public void ValueTupleRequiredWhenRightHandSideIsTupleButNoReferenceEmitted()
{
string source = @"
class C
{
public static void Main()
{
int x, y;
(x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
Action<PEAssembly> assemblyValidator = assembly =>
{
var reader = assembly.GetMetadataReader();
var names = reader.GetAssemblyRefNames().Select(name => reader.GetString(name));
Assert.Empty(names.Where(name => name.Contains("ValueTuple")));
};
CompileAndVerifyCommon(comp, assemblyValidator: assemblyValidator);
}
[Fact]
public void ValueTupleReturnMissingMemberWithCSharp7()
{
string source = @"
class C
{
public void M()
{
int x, y;
var nested = ((x, y) = (1, 2));
System.Console.Write(nested.x);
}
}
";
var comp = CreateCompilation(source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyDiagnostics(
// (8,37): error CS8305: Tuple element name 'x' is inferred. Please use language version 7.1 or greater to access an element by its inferred name.
// System.Console.Write(nested.x);
Diagnostic(ErrorCode.ERR_TupleInferredNamesNotAvailable, "x").WithArguments("x", "7.1").WithLocation(8, 37)
);
}
[Fact]
public void ValueTupleReturnWithInferredNamesWithCSharp7_1()
{
string source = @"
class C
{
public void M()
{
int x, y, Item1, Rest;
var a = ((x, y) = (1, 2));
var b = ((x, x) = (1, 2));
var c = ((_, x) = (1, 2));
var d = ((Item1, Rest) = (1, 2));
var nested = ((x, Item1, y, (_, x, x), (x, y)) = (1, 2, 3, (4, 5, 6), (7, 8)));
(int, int) f = ((x, y) = (1, 2));
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var declarations = nodes.OfType<VariableDeclaratorSyntax>();
Assert.Equal("(System.Int32 x, System.Int32 y) a", model.GetDeclaredSymbol(declarations.ElementAt(4)).ToTestDisplayString());
Assert.Equal("(System.Int32, System.Int32) b", model.GetDeclaredSymbol(declarations.ElementAt(5)).ToTestDisplayString());
Assert.Equal("(System.Int32, System.Int32 x) c", model.GetDeclaredSymbol(declarations.ElementAt(6)).ToTestDisplayString());
var x = (ILocalSymbol)model.GetDeclaredSymbol(declarations.ElementAt(7));
Assert.Equal("(System.Int32, System.Int32) d", x.ToTestDisplayString());
Assert.True(x.Type.GetSymbol().TupleElementNames.IsDefault);
Assert.Equal("(System.Int32 x, System.Int32, System.Int32 y, (System.Int32, System.Int32, System.Int32), (System.Int32 x, System.Int32 y)) nested",
model.GetDeclaredSymbol(declarations.ElementAt(8)).ToTestDisplayString());
};
var comp = CompileAndVerify(source,
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionDeclarationCanOnlyBeParsedAsStatement()
{
string source = @"
class C
{
public static void Main()
{
var z = ((var x, int y) = new C());
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,19): error CS8185: A declaration is not allowed in this context.
// var z = ((var x, int y) = new C());
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x").WithLocation(6, 19)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void Constraints_01()
{
string source = @"
using System;
class C
{
public void M()
{
(int x, var (err1, y)) = (0, new C()); // ok, no return value used
(ArgIterator err2, var err3) = M2(); // ok, no return value
foreach ((ArgIterator err4, var err5) in new[] { M2() }) // ok, no return value
{
}
}
public static (ArgIterator, ArgIterator) M2()
{
return (default(ArgIterator), default(ArgIterator));
}
public void Deconstruct(out ArgIterator a, out int b)
{
a = default(ArgIterator);
b = 2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (19,29): error CS1601: Cannot make reference to variable of type 'ArgIterator'
// public void Deconstruct(out ArgIterator a, out int b)
Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator a").WithArguments("System.ArgIterator").WithLocation(19, 29),
// (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument
// public static (ArgIterator, ArgIterator) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46),
// (14,46): error CS0306: The type 'ArgIterator' may not be used as a type argument
// public static (ArgIterator, ArgIterator) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("System.ArgIterator").WithLocation(14, 46),
// (16,17): error CS0306: The type 'ArgIterator' may not be used as a type argument
// return (default(ArgIterator), default(ArgIterator));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 17),
// (16,39): error CS0306: The type 'ArgIterator' may not be used as a type argument
// return (default(ArgIterator), default(ArgIterator));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(ArgIterator)").WithArguments("System.ArgIterator").WithLocation(16, 39)
);
}
[Fact]
public void Constraints_02()
{
string source = @"
unsafe class C
{
public void M()
{
(int x, var (err1, y)) = (0, new C()); // ok, no return value
(var err2, var err3) = M2(); // ok, no return value
foreach ((var err4, var err5) in new[] { M2() }) // ok, no return value
{
}
}
public static (int*, int*) M2()
{
return (default(int*), default(int*));
}
public void Deconstruct(out int* a, out int b)
{
a = default(int*);
b = 2;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (13,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32),
// (13,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(13, 32),
// (15,17): error CS0306: The type 'int*' may not be used as a type argument
// return (default(int*), default(int*));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 17),
// (15,32): error CS0306: The type 'int*' may not be used as a type argument
// return (default(int*), default(int*));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(int*)").WithArguments("int*").WithLocation(15, 32)
);
}
[Fact]
public void Constraints_03()
{
string source = @"
unsafe class C
{
public void M()
{
int ok;
int* err1, err2;
var t = ((ok, (err1, ok)) = (0, new C()));
var t2 = ((err1, err2) = M2());
}
public static (int*, int*) M2()
{
throw null;
}
public void Deconstruct(out int* a, out int b)
{
a = default(int*);
b = 2;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (12,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32),
// (12,32): error CS0306: The type 'int*' may not be used as a type argument
// public static (int*, int*) M2()
Diagnostic(ErrorCode.ERR_BadTypeArgument, "M2").WithArguments("int*").WithLocation(12, 32),
// (8,24): error CS0306: The type 'int*' may not be used as a type argument
// var t = ((ok, (err1, ok)) = (0, new C()));
Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(8, 24),
// (9,20): error CS0306: The type 'int*' may not be used as a type argument
// var t2 = ((err1, err2) = M2());
Diagnostic(ErrorCode.ERR_BadTypeArgument, "err1").WithArguments("int*").WithLocation(9, 20),
// (9,26): error CS0306: The type 'int*' may not be used as a type argument
// var t2 = ((err1, err2) = M2());
Diagnostic(ErrorCode.ERR_BadTypeArgument, "err2").WithArguments("int*").WithLocation(9, 26)
);
}
[Fact]
public void DeconstructionWithTupleNamesCannotBeParsed()
{
string source = @"
class C
{
public static void Main()
{
(Alice: var x, Bob: int y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,10): error CS8187: Tuple element names are not permitted on the left of a deconstruction.
// (Alice: var x, Bob: int y) = (1, 2);
Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Alice:").WithLocation(6, 10),
// (6,24): error CS8187: Tuple element names are not permitted on the left of a deconstruction.
// (Alice: var x, Bob: int y) = (1, 2);
Diagnostic(ErrorCode.ERR_TupleElementNamesInDeconstruction, "Bob:").WithLocation(6, 24)
);
}
[Fact]
public void ValueTupleReturnIsEmittedIfUsedInLambda()
{
string source = @"
class C
{
static void F(System.Action a) { }
static void F<T>(System.Func<T> f) { System.Console.Write(f().ToString()); }
static void Main()
{
int x, y;
F(() => (x, y) = (1, 2));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 2)");
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningIntoProperties()
{
string source = @"
class C
{
static int field;
static long x { set { System.Console.WriteLine($""setX {value}""); } }
static string y { get; set; }
static ref int z { get { return ref field; } }
static void Main()
{
(x, y, z) = new C();
System.Console.WriteLine(y);
System.Console.WriteLine($""field: {field}"");
}
public void Deconstruct(out int a, out string b, out int c)
{
a = 1;
b = ""hello"";
c = 2;
}
}
";
string expected =
@"setX 1
hello
field: 2
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningTupleIntoProperties()
{
string source = @"
class C
{
static int field;
static long x { set { System.Console.WriteLine($""setX {value}""); } }
static string y { get; set; }
static ref int z { get { return ref field; } }
static void Main()
{
(x, y, z) = (1, ""hello"", 2);
System.Console.WriteLine(y);
System.Console.WriteLine($""field: {field}"");
}
}
";
string expected =
@"setX 1
hello
field: 2
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")]
public void AssigningIntoIndexers()
{
string source = @"
using System;
class C
{
int field;
ref int this[int x, int y, int z, int opt = 1]
{
get
{
Console.WriteLine($""this.get"");
return ref field;
}
}
int this[int x, long y, int z, int opt = 1]
{
set
{
Console.WriteLine($""this.set({value})"");
}
}
int M(int i)
{
Console.WriteLine($""M({i})"");
return 0;
}
void Test()
{
(this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = this;
Console.WriteLine($""field: {field}"");
}
static void Main()
{
new C().Test();
}
void Deconstruct(out int a, out int b)
{
Console.WriteLine(nameof(Deconstruct));
a = 1;
b = 2;
}
}
";
var expectedOutput =
@"M(1)
M(2)
this.get
M(3)
M(4)
Deconstruct
this.set(2)
field: 1
";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(18554, "https://github.com/dotnet/roslyn/issues/18554")]
public void AssigningTupleIntoIndexers()
{
string source = @"
using System;
class C
{
int field;
ref int this[int x, int y, int z, int opt = 1]
{
get
{
Console.WriteLine($""this.get"");
return ref field;
}
}
int this[int x, long y, int z, int opt = 1]
{
set
{
Console.WriteLine($""this.set({value})"");
}
}
int M(int i)
{
Console.WriteLine($""M({i})"");
return 0;
}
void Test()
{
(this[z: M(1), x: M(2), y: 10], this[z: M(3), x: M(4), y: 10L]) = (1, 2);
Console.WriteLine($""field: {field}"");
}
static void Main()
{
new C().Test();
}
}
";
var expectedOutput =
@"M(1)
M(2)
this.get
M(3)
M(4)
this.set(2)
field: 1
";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningIntoIndexerWithOptionalValueParameter()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = (
01 00 04 49 74 65 6d 00 00
)
.method public hidebysig specialname
instance void set_Item (
int32 i,
[opt] int32 'value'
) cil managed
{
.param [2] = int32(1)
.maxstack 8
IL_0000: ldstr ""this.set({0})""
IL_0005: ldarg.2
IL_0006: box[mscorlib]System.Int32
IL_000b: call string[mscorlib] System.String::Format(string, object)
IL_0010: call void [mscorlib]System.Console::WriteLine(string)
IL_0015: ret
} // end of method C::set_Item
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
.property instance int32 Item(
int32 i
)
{
.set instance void C::set_Item(int32, int32)
}
} // end of class C
";
var source = @"
class Program
{
static void Main()
{
var c = new C();
(c[1], c[2]) = (1, 2);
}
}
";
string expectedOutput =
@"this.set(1)
this.set(2)
";
var comp = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: expectedOutput).VerifyDiagnostics();
}
[Fact]
public void Swap()
{
string source = @"
class C
{
static int x = 2;
static int y = 4;
static void Main()
{
Swap();
System.Console.WriteLine(x + "" "" + y);
}
static void Swap()
{
(x, y) = (y, x);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "4 2");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Swap", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int V_0)
IL_0000: ldsfld ""int C.y""
IL_0005: ldsfld ""int C.x""
IL_000a: stloc.0
IL_000b: stsfld ""int C.x""
IL_0010: ldloc.0
IL_0011: stsfld ""int C.y""
IL_0016: ret
}
");
}
[Fact]
public void CircularFlow()
{
string source = @"
class C
{
static void Main()
{
(object i, object ii) x = (1, 2);
object y;
(x.ii, y) = x;
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2");
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.RefLocalsReturns)]
public void CircularFlow2()
{
string source = @"
class C
{
static void Main()
{
(object i, object ii) x = (1,2);
object y;
ref var a = ref x;
(a.ii, y) = x;
System.Console.WriteLine(x + "" "" + y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 1) 2", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructUsingBaseDeconstructMethod()
{
string source = @"
class Base
{
public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
}
class C : Base
{
static void Main()
{
int x, y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int c) { c = 42; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
[Fact]
public void NestedDeconstructUsingSystemTupleExtensionMethod()
{
string source = @"
using System;
class C
{
static void Main()
{
int x;
string y, z;
(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""));
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello world", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree);
var deconstruction = (AssignmentExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.SimpleAssignmentExpression).AsNode();
Assert.Equal(@"(x, (y, z)) = Tuple.Create(1, Tuple.Create(""hello"", ""world""))", deconstruction.ToString());
var deconstructionInfo = model.GetDeconstructionInfo(deconstruction);
Assert.Equal("void System.TupleExtensions.Deconstruct<System.Int32, System.Tuple<System.String, System.String>>(" +
"this System.Tuple<System.Int32, System.Tuple<System.String, System.String>> value, " +
"out System.Int32 item1, out System.Tuple<System.String, System.String> item2)",
deconstructionInfo.Method.ToTestDisplayString());
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Equal("void System.TupleExtensions.Deconstruct<System.String, System.String>(" +
"this System.Tuple<System.String, System.String> value, " +
"out System.String item1, out System.String item2)",
nested[1].Method.ToTestDisplayString());
Assert.Null(nested[1].Conversion);
var nested2 = nested[1].Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested2[0].Method);
Assert.Equal(ConversionKind.Identity, nested2[0].Conversion.Value.Kind);
Assert.Empty(nested2[0].Nested);
Assert.Null(nested2[1].Method);
Assert.Equal(ConversionKind.Identity, nested2[1].Conversion.Value.Kind);
Assert.Empty(nested2[1].Nested);
}
[Fact]
public void DeconstructUsingValueTupleExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
int x;
string y, z;
(x, y, z) = (1, 2);
}
}
public static class Extensions
{
public static void Deconstruct(this (int, int) self, out int x, out string y, out string z)
{
throw null;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,25): error CS0029: Cannot implicitly convert type 'int' to 'string'
// (x, y, z) = (1, 2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(8, 25),
// (8,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// (x, y, z) = (1, 2);
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = (1, 2)").WithArguments("2", "3").WithLocation(8, 9)
);
}
[Fact]
public void OverrideDeconstruct()
{
string source = @"
class Base
{
public virtual void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
class C : Base
{
static void Main()
{
int x;
string y;
(x, y) = new C();
}
public override void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; System.Console.WriteLine(""override""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "override", parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructRefTuple()
{
string template = @"
using System;
class C
{
static void Main()
{
int VARIABLES; // int x1, x2, ...
(VARIABLES) = (TUPLE).ToTuple(); // (x1, x2, ...) = (1, 2, ...).ToTuple();
System.Console.WriteLine(OUTPUT);
}
}
";
for (int i = 2; i <= 21; i++)
{
var tuple = String.Join(", ", Enumerable.Range(1, i).Select(n => n.ToString()));
var variables = String.Join(", ", Enumerable.Range(1, i).Select(n => $"x{n}"));
var output = String.Join(@" + "" "" + ", Enumerable.Range(1, i).Select(n => $"x{n}"));
var expected = String.Join(" ", Enumerable.Range(1, i).Select(n => n));
var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple).Replace("OUTPUT", output);
var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular.WithRefsFeature());
comp.VerifyDiagnostics();
}
}
[Fact]
public void DeconstructExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
}
static class D
{
public static void Deconstruct(this C value, out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructRefExtensionMethod()
{
// https://github.com/dotnet/csharplang/blob/main/meetings/2018/LDM-2018-01-24.md
string source = @"
struct C
{
static void Main()
{
long x;
string y;
var c = new C();
(x, y) = c;
System.Console.WriteLine(x + "" "" + y);
}
}
static class D
{
public static void Deconstruct(this ref C value, out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (10,9): error CS1510: A ref or out value must be an assignable variable
// (x, y) = c;
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x, y) = c").WithLocation(10, 9)
);
}
[Fact]
public void DeconstructInExtensionMethod()
{
string source = @"
struct C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
System.Console.WriteLine(x + "" "" + y);
}
}
static class D
{
public static void Deconstruct(this in C value, out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void UnderspecifiedDeconstructGenericExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
}
}
static class Extension
{
public static void Deconstruct<T>(this C value, out int a, out T b)
{
a = 2;
b = default(T);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,18): error CS0411: The type arguments for method 'Extension.Deconstruct<T>(C, out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C()").WithArguments("Extension.Deconstruct<T>(C, out int, out T)").WithLocation(8, 18),
// (8,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 18)
);
}
[Fact]
public void UnspecifiedGenericMethodIsNotCandidate()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C();
}
}
static class Extension
{
public static void Deconstruct<T>(this C value, out int a, out T b)
{
a = 2;
b = default(T);
}
public static void Deconstruct(this C value, out int a, out string b)
{
a = 2;
b = ""hello"";
System.Console.Write(""Deconstructed"");
}
}";
var comp = CompileAndVerify(source, expectedOutput: "Deconstructed");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructGenericExtensionMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C1<string>();
}
}
public class C1<T> { }
static class Extension
{
public static void Deconstruct<T>(this C1<T> value, out int a, out T b)
{
a = 2;
b = default(T);
System.Console.WriteLine(""Deconstructed"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "Deconstructed");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructGenericMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C1();
}
}
class C1
{
public void Deconstruct<T>(out int a, out T b)
{
a = 2;
b = default(T);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,18): error CS0411: The type arguments for method 'C1.Deconstruct<T>(out int, out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// (x, y) = new C1();
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new C1()").WithArguments("C1.Deconstruct<T>(out int, out T)").WithLocation(9, 18),
// (9,18): error CS8129: No Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type.
// (x, y) = new C1();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 18)
);
}
[Fact]
public void AmbiguousDeconstructGenericMethod()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
(x, y) = new C1();
System.Console.Write($""{x} {y}"");
}
}
class C1
{
public void Deconstruct<T>(out int a, out T b)
{
a = 2;
b = default(T);
}
public void Deconstruct(out int a, out string b)
{
a = 2;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "2 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedTupleAssignment()
{
string source = @"
class C
{
static void Main()
{
long x;
string y, z;
(x, (y, z)) = ((int)1, (""a"", ""b""));
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(x, (y, z))", lhs.ToString());
Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int64 x, (System.String y, System.String z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "1 a b", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedTypelessTupleAssignment()
{
string source = @"
class C
{
static void Main()
{
string x, y, z;
(x, (y, z)) = (null, (null, null));
System.Console.WriteLine(""nothing"" + x + y + z);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "nothing");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedDeconstructAssignment()
{
string source = @"
class C
{
static void Main()
{
int x;
string y, z;
(x, (y, z)) = new D1();
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
class D1
{
public void Deconstruct(out int item1, out D2 item2)
{
item1 = 1;
item2 = new D2();
}
}
class D2
{
public void Deconstruct(out string item1, out string item2)
{
item1 = ""a"";
item2 = ""b"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 a b");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedMixedAssignment1()
{
string source = @"
class C
{
static void Main()
{
int x, y, z;
(x, (y, z)) = (1, new D1());
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
class D1
{
public void Deconstruct(out int item1, out int item2)
{
item1 = 2;
item2 = 3;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3");
comp.VerifyDiagnostics();
}
[Fact]
public void NestedMixedAssignment2()
{
string source = @"
class C
{
static void Main()
{
int x;
string y, z;
(x, (y, z)) = new D1();
System.Console.WriteLine(x + "" "" + y + "" "" + z);
}
}
class D1
{
public void Deconstruct(out int item1, out (string, string) item2)
{
item1 = 1;
item2 = (""a"", ""b"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 a b");
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyNestedExecutionOrder()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
(c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); }
}
class C1
{
public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
class D3
{
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforX
getHolderforY
getHolderforZ
getDeconstructReceiver
Deconstruct1
Deconstruct2
Conversion1
Conversion2
Conversion3
setX
setY
setZ
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyNestedExecutionOrder_Conditional()
{
string source = @"
using System;
class C
{
int x { set { Console.WriteLine($""setX""); } }
int y { set { Console.WriteLine($""setY""); } }
int z { set { Console.WriteLine($""setZ""); } }
C getHolderForX() { Console.WriteLine(""getHolderforX""); return this; }
C getHolderForY() { Console.WriteLine(""getHolderforY""); return this; }
C getHolderForZ() { Console.WriteLine(""getHolderforZ""); return this; }
C getDeconstructReceiver() { Console.WriteLine(""getDeconstructReceiver""); return this; }
static void Main()
{
C c = new C();
bool b = false;
(c.getHolderForX().x, (c.getHolderForY().y, c.getHolderForZ().z)) = b ? default : c.getDeconstructReceiver();
}
public void Deconstruct(out D1 x, out C1 t) { x = new D1(); t = new C1(); Console.WriteLine(""Deconstruct1""); }
}
class C1
{
public void Deconstruct(out D2 y, out D3 z) { y = new D2(); z = new D3(); Console.WriteLine(""Deconstruct2""); }
}
class D1
{
public static implicit operator int(D1 d) { Console.WriteLine(""Conversion1""); return 1; }
}
class D2
{
public static implicit operator int(D2 d) { Console.WriteLine(""Conversion2""); return 2; }
}
class D3
{
public static implicit operator int(D3 d) { Console.WriteLine(""Conversion3""); return 3; }
}
";
string expected =
@"getHolderforX
getHolderforY
getHolderforZ
getDeconstructReceiver
Deconstruct1
Deconstruct2
Conversion1
Conversion2
Conversion3
setX
setY
setZ
";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void VerifyNestedExecutionOrder2()
{
string source = @"
using System;
class C
{
static LongInteger x1 { set { Console.WriteLine($""setX1 {value}""); } }
static LongInteger x2 { set { Console.WriteLine($""setX2 {value}""); } }
static LongInteger x3 { set { Console.WriteLine($""setX3 {value}""); } }
static LongInteger x4 { set { Console.WriteLine($""setX4 {value}""); } }
static LongInteger x5 { set { Console.WriteLine($""setX5 {value}""); } }
static LongInteger x6 { set { Console.WriteLine($""setX6 {value}""); } }
static LongInteger x7 { set { Console.WriteLine($""setX7 {value}""); } }
static void Main()
{
((x1, (x2, x3)), ((x4, x5), (x6, x7))) = Pair.Create(Pair.Create(new Integer(1), Pair.Create(new Integer(2), new Integer(3))),
Pair.Create(Pair.Create(new Integer(4), new Integer(5)), Pair.Create(new Integer(6), new Integer(7))));
}
}
" + commonSource;
string expected =
@"Deconstructing ((1, (2, 3)), ((4, 5), (6, 7)))
Deconstructing (1, (2, 3))
Deconstructing (2, 3)
Deconstructing ((4, 5), (6, 7))
Deconstructing (4, 5)
Deconstructing (6, 7)
Converting 1
Converting 2
Converting 3
Converting 4
Converting 5
Converting 6
Converting 7
setX1 1
setX2 2
setX3 3
setX4 4
setX5 5
setX6 6
setX7 7";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void MixOfAssignments()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
C a, b, c;
c = new C();
(x, y) = a = b = c;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/12400")]
[WorkItem(12400, "https://github.com/dotnet/roslyn/issues/12400")]
public void AssignWithPostfixOperator()
{
string source = @"
class C
{
int state = 1;
static void Main()
{
long x;
string y;
C c = new C();
(x, y) = c++;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b)
{
a = state;
b = ""hello"";
}
public static C operator ++(C c1)
{
return new C() { state = 2 };
}
}
";
// https://github.com/dotnet/roslyn/issues/12400
// we expect "2 hello" instead, which means the evaluation order is wrong
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(13631, "https://github.com/dotnet/roslyn/issues/13631")]
public void DeconstructionDeclaration()
{
string source = @"
class C
{
static void Main()
{
var (x1, x2) = (1, ""hello"");
System.Console.WriteLine(x1 + "" "" + x2);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (int V_0, //x1
string V_1) //x2
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldstr ""hello""
IL_0007: stloc.1
IL_0008: ldloca.s V_0
IL_000a: call ""string int.ToString()""
IL_000f: ldstr "" ""
IL_0014: ldloc.1
IL_0015: call ""string string.Concat(string, string, string)""
IL_001a: call ""void System.Console.WriteLine(string)""
IL_001f: ret
}");
}
[Fact]
public void NestedVarDeconstructionDeclaration()
{
string source = @"
class C
{
static void Main()
{
var (x1, (x2, x3)) = (1, (2, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().First();
Assert.Equal(@"var (x1, (x2, x3))", lhs.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var lhsNested = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1);
Assert.Equal(@"(x2, x3)", lhsNested.ToString());
Assert.Null(model.GetTypeInfo(lhsNested).Type);
Assert.Null(model.GetSymbolInfo(lhsNested).Symbol);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionDeclaration_WithCSharp7_1()
{
string source = @"
class C
{
static void Main()
{
(int x1, var (x2, (x3, x4)), var x5) = (1, (2, (3, ""hello"")), 5);
System.Console.WriteLine($""{x1} {x2} {x3} {x4} {x5}"");
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(int x1, var (x2, (x3, x4)), var x5)", lhs.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, (System.Int32 x3, System.String x4)), System.Int32 x5)",
model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var x234 = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1);
Assert.Equal(@"var (x2, (x3, x4))", x234.ToString());
Assert.Equal("(System.Int32 x2, (System.Int32 x3, System.String x4))", model.GetTypeInfo(x234).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x234).Symbol);
var x34 = tree.GetRoot().DescendantNodes().OfType<ParenthesizedVariableDesignationSyntax>().ElementAt(1);
Assert.Equal(@"(x3, x4)", x34.ToString());
Assert.Null(model.GetTypeInfo(x34).Type);
Assert.Null(model.GetSymbolInfo(x34).Symbol);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
var x4 = GetDeconstructionVariable(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForDeconstructionLocal(model, x4, x4Ref);
var x5 = GetDeconstructionVariable(tree, "x5");
var x5Ref = GetReference(tree, "x5");
VerifyModelForDeconstructionLocal(model, x5, x5Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 hello 5",
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionAssignment_WithCSharp7_1()
{
string source = @"
class C
{
static void Main()
{
int x1, x2, x3;
(x1, (x2, x3)) = (1, (2, 3));
System.Console.WriteLine($""{x1} {x2} {x3}"");
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x123 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(x1, (x2, x3))", x123.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.Int32 x3))",
model.GetTypeInfo(x123).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x123).Symbol);
var x23 = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(x2, x3)", x23.ToString());
Assert.Equal("(System.Int32 x2, System.Int32 x3)", model.GetTypeInfo(x23).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x23).Symbol);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3",
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionDeclaration2()
{
string source = @"
class C
{
static void Main()
{
(var x1, var (x2, x3)) = (1, (2, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal("(var x1, var (x2, x3))", lhs.ToString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x1, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1);
Assert.Equal("var (x2, x3)", lhsNested.ToString());
Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhsNested).Symbol);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void NestedVarDeconstructionDeclarationWithCSharp7_1()
{
string source = @"
class C
{
static void Main()
{
(var x1, byte _, var (x2, x3)) = (1, 2, (3, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal("(var x1, byte _, var (x2, x3))", lhs.ToString());
Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x1, System.Byte, (System.Int32 x2, System.String x3))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhs).Symbol);
var lhsNested = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(2);
Assert.Equal("var (x2, x3)", lhsNested.ToString());
Assert.Equal("(System.Int32 x2, System.String x3)", model.GetTypeInfo(lhsNested).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(lhsNested).Symbol);
};
var comp = CompileAndVerify(source, sourceSymbolValidator: validator,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyDiagnostics();
}
[Fact]
public void NestedDeconstructionDeclaration()
{
string source = @"
class C
{
static void Main()
{
(int x1, (int x2, string x3)) = (1, (2, ""hello""));
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 hello", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void VarMethodExists()
{
string source = @"
class C
{
static void Main()
{
int x1 = 1;
int x2 = 1;
var (x1, x2);
}
static void var(int a, int b) { System.Console.WriteLine(""var""); }
}
";
var comp = CompileAndVerify(source, expectedOutput: "var");
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess1()
{
string source = @"
class C
{
static void Main()
{
(var (x1, x2), string x3) = ((1, 2), null);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: " 1 2");
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess2()
{
string source = @"
class C
{
static void Main()
{
(string x1, byte x2, var x3) = (null, 2, 3);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(string x1, byte x2, var x3)", lhs.ToString());
Assert.Equal("(System.String x1, System.Byte x2, System.Int32 x3)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(null, 2, 3)", literal.ToString());
Assert.Null(model.GetTypeInfo(literal).Type);
Assert.Equal("(System.String, System.Byte, System.Int32)", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind);
};
var comp = CompileAndVerify(source, expectedOutput: " 2 3", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess3()
{
string source = @"
class C
{
static void Main()
{
(string x1, var x2) = (null, (1, 2));
System.Console.WriteLine(x1 + "" "" + x2);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().First();
Assert.Equal(@"(string x1, var x2)", lhs.ToString());
Assert.Equal("(System.String x1, (System.Int32, System.Int32) x2)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
var literal = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(null, (1, 2))", literal.ToString());
Assert.Null(model.GetTypeInfo(literal).Type);
Assert.Equal("(System.String, (System.Int32, System.Int32))", model.GetTypeInfo(literal).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.ImplicitTupleLiteral, model.GetConversion(literal).Kind);
var nestedLiteral = literal.Arguments[1].Expression;
Assert.Equal(@"(1, 2)", nestedLiteral.ToString());
Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).Type.ToTestDisplayString());
Assert.Equal("(System.Int32, System.Int32)", model.GetTypeInfo(nestedLiteral).ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.Identity, model.GetConversion(nestedLiteral).Kind);
};
var comp = CompileAndVerify(source, expectedOutput: " (1, 2)", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void TypeMergingSuccess4()
{
string source = @"
class C
{
static void Main()
{
((string x1, byte x2, var x3), int x4) = (M(), 4);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4);
}
static (string, byte, int) M() { return (null, 2, 3); }
}
";
var comp = CompileAndVerify(source, expectedOutput: " 2 3 4");
comp.VerifyDiagnostics();
}
[Fact]
public void VarVarDeclaration()
{
string source = @"
class C
{
static void Main()
{
(var (x1, x2), var x3) = Pair.Create(Pair.Create(1, ""hello""), 2);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
" + commonSource;
string expected =
@"Deconstructing ((1, hello), 2)
Deconstructing (1, hello)
1 hello 2";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
};
var comp = CompileAndVerify(source, expectedOutput: expected, parseOptions: TestOptions.Regular,
sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
private static void VerifyModelForDeconstructionLocal(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.DeconstructionVariable, references);
}
private static void VerifyModelForLocal(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references)
{
VerifyModelForDeconstruction(model, decl, kind, references);
}
private static void VerifyModelForDeconstructionForeach(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references)
{
VerifyModelForDeconstruction(model, decl, LocalDeclarationKind.ForEachIterationVariable, references);
}
private static void VerifyModelForDeconstruction(SemanticModel model, SingleVariableDesignationSyntax decl, LocalDeclarationKind kind, params IdentifierNameSyntax[] references)
{
var symbol = model.GetDeclaredSymbol(decl);
Assert.Equal(decl.Identifier.ValueText, symbol.Name);
Assert.Equal(kind, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)decl));
Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText));
var local = symbol.GetSymbol<SourceLocalSymbol>();
var typeSyntax = GetTypeSyntax(decl);
if (local.IsVar && local.Type.IsErrorType())
{
Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
}
else
{
if (typeSyntax != null)
{
Assert.Equal(local.Type.GetPublicSymbol(), model.GetSymbolInfo(typeSyntax).Symbol);
}
}
foreach (var reference in references)
{
Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText));
Assert.Equal(local.Type.GetPublicSymbol(), model.GetTypeInfo(reference).Type);
}
}
private static void VerifyModelForDeconstructionField(SemanticModel model, SingleVariableDesignationSyntax decl, params IdentifierNameSyntax[] references)
{
var field = (IFieldSymbol)model.GetDeclaredSymbol(decl);
Assert.Equal(decl.Identifier.ValueText, field.Name);
Assert.Equal(SymbolKind.Field, field.Kind);
Assert.Same(field, model.GetDeclaredSymbol((SyntaxNode)decl));
Assert.Same(field, model.LookupSymbols(decl.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.Equal(Accessibility.Private, field.DeclaredAccessibility);
Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier.ValueText));
foreach (var reference in references)
{
Assert.Same(field, model.GetSymbolInfo(reference).Symbol);
Assert.Same(field, model.LookupSymbols(reference.SpanStart, name: decl.Identifier.ValueText).Single());
Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier.ValueText));
Assert.Equal(field.Type, model.GetTypeInfo(reference).Type);
}
}
private static TypeSyntax GetTypeSyntax(SingleVariableDesignationSyntax decl)
{
return (decl.Parent as DeclarationExpressionSyntax)?.Type;
}
private static SingleVariableDesignationSyntax GetDeconstructionVariable(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single();
}
private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>();
}
private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken);
}
private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name)
{
return GetReferences(tree, name).Single();
}
private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count)
{
var nameRef = GetReferences(tree, name).ToArray();
Assert.Equal(count, nameRef.Length);
return nameRef;
}
private static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name)
{
return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name);
}
[Fact]
public void DeclarationWithActualVarType()
{
string source = @"
class C
{
static void Main()
{
(var x1, int x2) = (new var(), 2);
System.Console.WriteLine(x1 + "" "" + x2);
}
}
class var
{
public override string ToString() { return ""var""; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void DeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
(var x1, var x2) = (1, 2);
var (x3, x4) = (3, 4);
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4);
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionLocal(model, x3, x3Ref);
var x4 = GetDeconstructionVariable(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForDeconstructionLocal(model, x4, x4Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x1Type));
var x34Var = (DeclarationExpressionSyntax)x3.Parent.Parent;
Assert.Equal("var", x34Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x34Var.Type).Symbol); // The var in `var (x3, x4)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void DeclarationWithAliasedVarType()
{
string source = @"
using var = D;
class C
{
static void Main()
{
(var x1, int x2) = (new var(), 2);
System.Console.WriteLine(x1 + "" "" + x2);
}
}
class D
{
public override string ToString() { return ""var""; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("D", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
var x1Alias = model.GetAliasInfo(x1Type);
Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind);
Assert.Equal("D", x1Alias.Target.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x2Type));
};
var comp = CompileAndVerify(source, expectedOutput: "var 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
for (var (x1, x2) = (1, 2); x1 < 2; (x1, x2) = (x1 + 1, x2 + 1))
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 4);
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReferences(tree, "x2", 3);
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForWithVarDeconstructInitializersCanParse()
{
string source = @"
using System;
class C
{
static void Main()
{
int x3;
for (var (x1, x2) = (1, 2), x3 = 3; true; )
{
Console.WriteLine(x1);
Console.WriteLine(x2);
Console.WriteLine(x3);
break;
}
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
};
var comp = CompileAndVerify(source, expectedOutput: @"1
2
3", sourceSymbolValidator: validator);
comp.VerifyDiagnostics(
// this is permitted now, as it is just an assignment expression
);
}
[Fact]
public void ForWithActualVarType()
{
string source = @"
class C
{
static void Main()
{
for ((int x1, var x2) = (1, new var()); x1 < 2; x1++)
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
class var
{
public override string ToString() { return ""var""; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 3);
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "1 var", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForWithTypes()
{
string source = @"
class C
{
static void Main()
{
for ((int x1, var x2) = (1, 2); x1 < 2; x1++)
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1", 3);
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
// extra checks on x1
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
// extra checks on x2
var x2Type = GetTypeSyntax(x2);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x2Type).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(x2Type).Symbol.ToDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachIEnumerableDeclarationWithImplicitVarType()
{
string source = @"
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
Print(x1, x2);
}
}
static IEnumerable<(int, int)> M() { yield return (1, 2); }
static void Print(object a, object b) { System.Console.WriteLine(a + "" "" + b); }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Equal("(System.Int32 x1, System.Int32 x2)", model.GetTypeInfo(x12Var).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
// verify deconstruction info
var deconstructionForeach = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single();
var deconstructionInfo = model.GetDeconstructionInfo(deconstructionForeach);
Assert.Null(deconstructionInfo.Method);
Assert.Null(deconstructionInfo.Conversion);
var nested = deconstructionInfo.Nested;
Assert.Equal(2, nested.Length);
Assert.Null(nested[0].Method);
Assert.Equal(ConversionKind.Identity, nested[0].Conversion.Value.Kind);
Assert.Empty(nested[0].Nested);
Assert.Null(nested[1].Method);
Assert.Equal(ConversionKind.Identity, nested[1].Conversion.Value.Kind);
Assert.Empty(nested[1].Nested);
};
var comp = CompileAndVerify(source, expectedOutput: "1 2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
var comp7_1 = CompileAndVerify(source, expectedOutput: "1 2",
sourceSymbolValidator: validator, parseOptions: TestOptions.Regular7_1);
comp7_1.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> V_0,
int V_1, //x1
int V_2) //x2
IL_0000: call ""System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>> C.M()""
IL_0005: callvirt ""System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>> System.Collections.Generic.IEnumerable<System.ValueTuple<int, int>>.GetEnumerator()""
IL_000a: stloc.0
.try
{
IL_000b: br.s IL_0031
IL_000d: ldloc.0
IL_000e: callvirt ""System.ValueTuple<int, int> System.Collections.Generic.IEnumerator<System.ValueTuple<int, int>>.Current.get""
IL_0013: dup
IL_0014: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0019: stloc.1
IL_001a: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: box ""int""
IL_0026: ldloc.2
IL_0027: box ""int""
IL_002c: call ""void C.Print(object, object)""
IL_0031: ldloc.0
IL_0032: callvirt ""bool System.Collections.IEnumerator.MoveNext()""
IL_0037: brtrue.s IL_000d
IL_0039: leave.s IL_0045
}
finally
{
IL_003b: ldloc.0
IL_003c: brfalse.s IL_0044
IL_003e: ldloc.0
IL_003f: callvirt ""void System.IDisposable.Dispose()""
IL_0044: endfinally
}
IL_0045: ret
}");
}
[Fact]
public void ForEachSZArrayDeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" - "");
}
}
static (int, int)[] M() { return new[] { (1, 2), (3, 4) }; }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
var symbol = model.GetDeclaredSymbol(x1);
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 75 (0x4b)
.maxstack 4
.locals init (System.ValueTuple<int, int>[] V_0,
int V_1,
int V_2, //x1
int V_3) //x2
IL_0000: call ""System.ValueTuple<int, int>[] C.M()""
IL_0005: stloc.0
IL_0006: ldc.i4.0
IL_0007: stloc.1
IL_0008: br.s IL_0044
IL_000a: ldloc.0
IL_000b: ldloc.1
IL_000c: ldelem ""System.ValueTuple<int, int>""
IL_0011: dup
IL_0012: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0017: stloc.2
IL_0018: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_001d: stloc.3
IL_001e: ldloca.s V_2
IL_0020: call ""string int.ToString()""
IL_0025: ldstr "" ""
IL_002a: ldloca.s V_3
IL_002c: call ""string int.ToString()""
IL_0031: ldstr "" - ""
IL_0036: call ""string string.Concat(string, string, string, string)""
IL_003b: call ""void System.Console.Write(string)""
IL_0040: ldloc.1
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.1
IL_0044: ldloc.1
IL_0045: ldloc.0
IL_0046: ldlen
IL_0047: conv.i4
IL_0048: blt.s IL_000a
IL_004a: ret
}");
}
[Fact]
public void ForEachMDArrayDeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
Print(x1, x2);
}
}
static (int, int)[,] M() { return new (int, int)[2, 2] { { (1, 2), (3, 4) }, { (5, 6), (7, 8) } }; }
static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 - 5 6 - 7 8 -", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 106 (0x6a)
.maxstack 3
.locals init (System.ValueTuple<int, int>[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4,
int V_5, //x1
int V_6) //x2
IL_0000: call ""System.ValueTuple<int, int>[,] C.M()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.0
IL_0008: callvirt ""int System.Array.GetUpperBound(int)""
IL_000d: stloc.1
IL_000e: ldloc.0
IL_000f: ldc.i4.1
IL_0010: callvirt ""int System.Array.GetUpperBound(int)""
IL_0015: stloc.2
IL_0016: ldloc.0
IL_0017: ldc.i4.0
IL_0018: callvirt ""int System.Array.GetLowerBound(int)""
IL_001d: stloc.3
IL_001e: br.s IL_0065
IL_0020: ldloc.0
IL_0021: ldc.i4.1
IL_0022: callvirt ""int System.Array.GetLowerBound(int)""
IL_0027: stloc.s V_4
IL_0029: br.s IL_005c
IL_002b: ldloc.0
IL_002c: ldloc.3
IL_002d: ldloc.s V_4
IL_002f: call ""(int, int)[*,*].Get""
IL_0034: dup
IL_0035: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_003a: stloc.s V_5
IL_003c: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0041: stloc.s V_6
IL_0043: ldloc.s V_5
IL_0045: box ""int""
IL_004a: ldloc.s V_6
IL_004c: box ""int""
IL_0051: call ""void C.Print(object, object)""
IL_0056: ldloc.s V_4
IL_0058: ldc.i4.1
IL_0059: add
IL_005a: stloc.s V_4
IL_005c: ldloc.s V_4
IL_005e: ldloc.2
IL_005f: ble.s IL_002b
IL_0061: ldloc.3
IL_0062: ldc.i4.1
IL_0063: add
IL_0064: stloc.3
IL_0065: ldloc.3
IL_0066: ldloc.1
IL_0067: ble.s IL_0020
IL_0069: ret
}");
}
[Fact]
public void ForEachStringDeclarationWithImplicitVarType()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M())
{
Print(x1, x2);
}
}
static string M() { return ""123""; }
static void Print(object a, object b) { System.Console.Write(a + "" "" + b + "" - ""); }
}
static class Extension
{
public static void Deconstruct(this char value, out int item1, out int item2)
{
item1 = item2 = System.Int32.Parse(value.ToString());
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
// extra check on var
var x12Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x12Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x12Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 1 - 2 2 - 3 3 - ", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 60 (0x3c)
.maxstack 3
.locals init (string V_0,
int V_1,
int V_2, //x2
int V_3,
int V_4)
IL_0000: call ""string C.M()""
IL_0005: stloc.0
IL_0006: ldc.i4.0
IL_0007: stloc.1
IL_0008: br.s IL_0032
IL_000a: ldloc.0
IL_000b: ldloc.1
IL_000c: callvirt ""char string.this[int].get""
IL_0011: ldloca.s V_3
IL_0013: ldloca.s V_4
IL_0015: call ""void Extension.Deconstruct(char, out int, out int)""
IL_001a: ldloc.3
IL_001b: ldloc.s V_4
IL_001d: stloc.2
IL_001e: box ""int""
IL_0023: ldloc.2
IL_0024: box ""int""
IL_0029: call ""void C.Print(object, object)""
IL_002e: ldloc.1
IL_002f: ldc.i4.1
IL_0030: add
IL_0031: stloc.1
IL_0032: ldloc.1
IL_0033: ldloc.0
IL_0034: callvirt ""int string.Length.get""
IL_0039: blt.s IL_000a
IL_003b: ret
}");
}
[Fact]
[WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")]
public void ForEachCollectionSymbol()
{
string source = @"
using System.Collections.Generic;
class Deconstructable
{
void M(IEnumerable<Deconstructable> x)
{
foreach (var (y1, y2) in x)
{
}
}
void Deconstruct(out int i, out int j) { i = 0; j = 0; }
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var collection = tree.GetRoot().DescendantNodes().OfType<ForEachVariableStatementSyntax>().Single().Expression;
Assert.Equal("x", collection.ToString());
var symbol = model.GetSymbolInfo(collection).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.Equal("x", symbol.Name);
Assert.Equal("System.Collections.Generic.IEnumerable<Deconstructable> x", symbol.ToTestDisplayString());
}
[Fact]
public void ForEachIEnumerableDeclarationWithNesting()
{
string source = @"
using System.Collections.Generic;
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3), (int x4, int x5)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - "");
}
}
static IEnumerable<(int, (int, int), (int, int))> M() { yield return (1, (2, 3), (4, 5)); yield return (6, (7, 8), (9, 10)); }
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionForeach(model, x3, x3Ref);
var x4 = GetDeconstructionVariable(tree, "x4");
var x4Ref = GetReference(tree, "x4");
VerifyModelForDeconstructionForeach(model, x4, x4Ref);
var x5 = GetDeconstructionVariable(tree, "x5");
var x5Ref = GetReference(tree, "x5");
VerifyModelForDeconstructionForeach(model, x5, x5Ref);
// extra check on var
var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent;
Assert.Equal("var", x23Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol
};
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -", sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachSZArrayDeclarationWithNesting()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3), (int x4, int x5)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - "");
}
}
static (int, (int, int), (int, int))[] M() { return new[] { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) }; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachMDArrayDeclarationWithNesting()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3), (int x4, int x5)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" "" + x4 + "" "" + x5 + "" - "");
}
}
static (int, (int, int), (int, int))[,] M() { return new(int, (int, int), (int, int))[1, 2] { { (1, (2, 3), (4, 5)), (6, (7, 8), (9, 10)) } }; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3 4 5 - 6 7 8 9 10 -");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachStringDeclarationWithNesting()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3)) in M())
{
System.Console.Write(x1 + "" "" + x2 + "" "" + x3 + "" - "");
}
}
static string M() { return ""12""; }
}
static class Extension
{
public static void Deconstruct(this char value, out int item1, out (int, int) item2)
{
item1 = System.Int32.Parse(value.ToString());
item2 = (item1, item1);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 1 1 - 2 2 2 - ");
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructExtensionOnInterface()
{
string source = @"
public interface Interface { }
class C : Interface
{
static void Main()
{
var (x, y) = new C();
System.Console.Write($""{x} {y}"");
}
}
static class Extension
{
public static void Deconstruct(this Interface value, out int item1, out string item2)
{
item1 = 42;
item2 = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "42 hello");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachIEnumerableDeclarationWithDeconstruct()
{
string source = @"
using System.Collections.Generic;
class C
{
static void Main()
{
foreach ((long x1, var (x2, x3)) in M())
{
Print(x1, x2, x3);
}
}
static IEnumerable<Pair<int, Pair<int, int>>> M() { yield return Pair.Create(1, Pair.Create(2, 3)); yield return Pair.Create(4, Pair.Create(5, 6)); }
static void Print(object a, object b, object c) { System.Console.WriteLine(a + "" "" + b + "" "" + c); }
}
" + commonSource;
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionForeach(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionForeach(model, x2, x2Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Ref = GetReference(tree, "x3");
VerifyModelForDeconstructionForeach(model, x3, x3Ref);
// extra check on var
var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent;
Assert.Equal("var", x23Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol
};
string expected =
@"Deconstructing (1, (2, 3))
Deconstructing (2, 3)
1 2 3
Deconstructing (4, (5, 6))
Deconstructing (5, 6)
4 5 6";
var comp = CompileAndVerify(source, expectedOutput: expected, sourceSymbolValidator: validator);
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main",
@"{
// Code size 90 (0x5a)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> V_0,
int V_1, //x2
int V_2, //x3
int V_3,
Pair<int, int> V_4,
int V_5,
int V_6)
IL_0000: call ""System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>> C.M()""
IL_0005: callvirt ""System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>> System.Collections.Generic.IEnumerable<Pair<int, Pair<int, int>>>.GetEnumerator()""
IL_000a: stloc.0
.try
{
IL_000b: br.s IL_0045
IL_000d: ldloc.0
IL_000e: callvirt ""Pair<int, Pair<int, int>> System.Collections.Generic.IEnumerator<Pair<int, Pair<int, int>>>.Current.get""
IL_0013: ldloca.s V_3
IL_0015: ldloca.s V_4
IL_0017: callvirt ""void Pair<int, Pair<int, int>>.Deconstruct(out int, out Pair<int, int>)""
IL_001c: ldloc.s V_4
IL_001e: ldloca.s V_5
IL_0020: ldloca.s V_6
IL_0022: callvirt ""void Pair<int, int>.Deconstruct(out int, out int)""
IL_0027: ldloc.3
IL_0028: conv.i8
IL_0029: ldloc.s V_5
IL_002b: stloc.1
IL_002c: ldloc.s V_6
IL_002e: stloc.2
IL_002f: box ""long""
IL_0034: ldloc.1
IL_0035: box ""int""
IL_003a: ldloc.2
IL_003b: box ""int""
IL_0040: call ""void C.Print(object, object, object)""
IL_0045: ldloc.0
IL_0046: callvirt ""bool System.Collections.IEnumerator.MoveNext()""
IL_004b: brtrue.s IL_000d
IL_004d: leave.s IL_0059
}
finally
{
IL_004f: ldloc.0
IL_0050: brfalse.s IL_0058
IL_0052: ldloc.0
IL_0053: callvirt ""void System.IDisposable.Dispose()""
IL_0058: endfinally
}
IL_0059: ret
}
");
}
[Fact]
public void ForEachSZArrayDeclarationWithDeconstruct()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3)) in M())
{
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
static Pair<int, Pair<int, int>>[] M() { return new[] { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) }; }
}
" + commonSource;
string expected =
@"Deconstructing (1, (2, 3))
Deconstructing (2, 3)
1 2 3
Deconstructing (4, (5, 6))
Deconstructing (5, 6)
4 5 6";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachMDArrayDeclarationWithDeconstruct()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, var (x2, x3)) in M())
{
System.Console.WriteLine(x1 + "" "" + x2 + "" "" + x3);
}
}
static Pair<int, Pair<int, int>>[,] M() { return new Pair<int, Pair<int, int>> [1, 2] { { Pair.Create(1, Pair.Create(2, 3)), Pair.Create(4, Pair.Create(5, 6)) } }; }
}
" + commonSource;
string expected =
@"Deconstructing (1, (2, 3))
Deconstructing (2, 3)
1 2 3
Deconstructing (4, (5, 6))
Deconstructing (5, 6)
4 5 6";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachWithExpressionBody()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in new[] { (1, 2), (3, 4) })
System.Console.Write(x1 + "" "" + x2 + "" - "");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 - 3 4 -");
comp.VerifyDiagnostics();
}
[Fact]
public void ForEachCreatesNewVariables()
{
string source = @"
class C
{
static void Main()
{
var lambdas = new System.Action[2];
int index = 0;
foreach (var (x1, x2) in M())
{
lambdas[index] = () => { System.Console.Write(x1 + "" ""); };
index++;
}
lambdas[0]();
lambdas[1]();
}
static (int, int)[] M() { return new[] { (0, 0), (10, 10) }; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "0 10 ");
comp.VerifyDiagnostics();
}
[Fact]
public void TupleDeconstructionIntoDynamicArrayIndexer()
{
string source = @"
class C
{
static void Main()
{
dynamic x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic x)
{
(x[0], x[1]) = (""hello"", ""world"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void IntTupleDeconstructionIntoDynamicArrayIndexer()
{
string source = @"
class C
{
static void Main()
{
dynamic x = new int[] { 1, 2 };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic x)
{
(x[0], x[1]) = (3, 4);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionIntoDynamicArrayIndexer()
{
string source = @"
class C
{
static void Main()
{
dynamic x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic x)
{
(x[0], x[1]) = new C();
}
public void Deconstruct(out string a, out string b)
{
a = ""hello"";
b = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void TupleDeconstructionIntoDynamicArray()
{
string source = @"
class C
{
static void Main()
{
dynamic[] x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic[] x)
{
(x[0], x[1]) = (""hello"", ""world"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionIntoDynamicArray()
{
string source = @"
class C
{
static void Main()
{
dynamic[] x = new string[] { """", """" };
M(x);
System.Console.WriteLine($""{x[0]} {x[1]}"");
}
static void M(dynamic[] x)
{
(x[0], x[1]) = new C();
}
public void Deconstruct(out string a, out string b)
{
a = ""hello"";
b = ""world"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "hello world", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructionIntoDynamicMember()
{
string source = @"
class C
{
static void Main()
{
dynamic x = System.ValueTuple.Create(1, 2);
(x.Item1, x.Item2) = new C();
System.Console.WriteLine($""{x.Item1} {x.Item2}"");
}
public void Deconstruct(out int a, out int b)
{
a = 3;
b = 4;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "3 4", references: new[] { CSharpRef });
comp.VerifyDiagnostics();
}
[Fact]
public void FieldAndLocalWithSameName()
{
string source = @"
class C
{
public int x = 3;
static void Main()
{
new C().M();
}
void M()
{
var (x, y) = (1, 2);
System.Console.Write($""{x} {y} {this.x}"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 2 3");
comp.VerifyDiagnostics();
}
[Fact]
public void NoGlobalDeconstructionUnlessScript()
{
string source = @"
class C
{
var (x, y) = (1, 2);
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,11): error CS1001: Identifier expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(4, 11),
// (4,14): error CS1001: Identifier expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14),
// (4,16): error CS1002: ; expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(4, 16),
// (4,16): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(4, 16),
// (4,19): error CS1031: Type expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_TypeExpected, "1").WithLocation(4, 19),
// (4,19): error CS8124: Tuple must contain at least two elements.
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_TupleTooFewElements, "1").WithLocation(4, 19),
// (4,19): error CS1026: ) expected
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_CloseParenExpected, "1").WithLocation(4, 19),
// (4,19): error CS1519: Invalid token '1' in class, record, struct, or interface member declaration
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "1").WithArguments("1").WithLocation(4, 19),
// (4,5): error CS1520: Method must have a return type
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_MemberNeedsType, "var").WithLocation(4, 5),
// (4,5): error CS0501: 'C.C(x, y)' must declare a body because it is not marked abstract, extern, or partial
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "var").WithArguments("C.C(x, y)").WithLocation(4, 5),
// (4,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(4, 10),
// (4,13): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?)
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(4, 13)
);
var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf();
Assert.False(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression));
}
[Fact]
public void SimpleDeconstructionInScript()
{
var source =
@"
using alias = System.Int32;
(string x, alias y) = (""hello"", 42);
System.Console.Write($""{x} {y}"");
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
var xRef = GetReference(tree, "x");
Assert.Equal("System.String Script.x", xSymbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x, xRef);
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
var yRef = GetReference(tree, "y");
Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, y, yRef);
// extra checks on x
var xType = GetTypeSyntax(x);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(xType).Symbol.Kind);
Assert.Equal("string", model.GetSymbolInfo(xType).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(xType));
// extra checks on y
var yType = GetTypeSyntax(y);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(yType).Symbol.Kind);
Assert.Equal("int", model.GetSymbolInfo(yType).Symbol.ToDisplayString());
Assert.Equal("alias=System.Int32", model.GetAliasInfo(yType).ToTestDisplayString());
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42", sourceSymbolValidator: validator);
verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 129 (0x81)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldarg.0
IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_000d: ldstr ""hello""
IL_0012: stfld ""string x""
IL_0017: ldarg.0
IL_0018: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_001d: ldc.i4.s 42
IL_001f: stfld ""int y""
IL_0024: ldstr ""{0} {1}""
IL_0029: ldarg.0
IL_002a: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_002f: ldfld ""string x""
IL_0034: ldarg.0
IL_0035: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_003a: ldfld ""int y""
IL_003f: box ""int""
IL_0044: call ""string string.Format(string, object, object)""
IL_0049: call ""void System.Console.Write(string)""
IL_004e: nop
IL_004f: ldnull
IL_0050: stloc.1
IL_0051: leave.s IL_006b
}
catch System.Exception
{
IL_0053: stloc.2
IL_0054: ldarg.0
IL_0055: ldc.i4.s -2
IL_0057: stfld ""int <<Initialize>>d__0.<>1__state""
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_0062: ldloc.2
IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)""
IL_0068: nop
IL_0069: leave.s IL_0080
}
IL_006b: ldarg.0
IL_006c: ldc.i4.s -2
IL_006e: stfld ""int <<Initialize>>d__0.<>1__state""
IL_0073: ldarg.0
IL_0074: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_0079: ldloc.1
IL_007a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)""
IL_007f: nop
IL_0080: ret
}");
}
[Fact]
public void GlobalDeconstructionOutsideScript()
{
var source =
@"
(string x, int y) = (""hello"", 42);
System.Console.Write(x);
System.Console.Write(y);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var nodes = comp.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf();
Assert.True(nodes.Any(n => n.Kind() == SyntaxKind.SimpleAssignmentExpression));
CompileAndVerify(comp, expectedOutput: "hello42");
}
[Fact]
public void NestedDeconstructionInScript()
{
var source =
@"
(string x, (int y, int z)) = (""hello"", (42, 43));
System.Console.Write($""{x} {y} {z}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43");
}
[Fact]
public void VarDeconstructionInScript()
{
var source =
@"
(var x, var y) = (""hello"", 42);
System.Console.Write($""{x} {y}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42");
}
[Fact]
public void NestedVarDeconstructionInScript()
{
var source =
@"
(var x1, var (x2, x3)) = (""hello"", (42, 43));
System.Console.Write($""{x1} {x2} {x3}"");
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.String Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
var x2Ref = GetReference(tree, "x2");
Assert.Equal("System.Int32 Script.x2", x2Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x2, x2Ref);
// extra checks on x1's var
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("string", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x1Type));
// extra check on x2 and x3's var
var x23Var = (DeclarationExpressionSyntax)x2.Parent.Parent;
Assert.Equal("var", x23Var.Type.ToString());
Assert.Null(model.GetSymbolInfo(x23Var.Type).Symbol); // The var in `var (x2, x3)` has no symbol
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 43", sourceSymbolValidator: validator);
}
[Fact]
public void EvaluationOrderForDeconstructionInScript()
{
var source =
@"
(int, int) M(out int x) { x = 1; return (2, 3); }
var (x2, x3) = M(out var x1);
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "1 2 3");
verifier.VerifyIL("<<Initialize>>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 178 (0xb2)
.maxstack 4
.locals init (int V_0,
object V_1,
System.ValueTuple<int, int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int <<Initialize>>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldarg.0
IL_0008: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_000d: ldarg.0
IL_000e: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_0013: ldflda ""int x1""
IL_0018: call ""System.ValueTuple<int, int> M(out int)""
IL_001d: stloc.2
IL_001e: ldarg.0
IL_001f: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_0024: ldloc.2
IL_0025: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002a: stfld ""int x2""
IL_002f: ldarg.0
IL_0030: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_0035: ldloc.2
IL_0036: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_003b: stfld ""int x3""
IL_0040: ldstr ""{0} {1} {2}""
IL_0045: ldarg.0
IL_0046: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_004b: ldfld ""int x1""
IL_0050: box ""int""
IL_0055: ldarg.0
IL_0056: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_005b: ldfld ""int x2""
IL_0060: box ""int""
IL_0065: ldarg.0
IL_0066: ldfld ""Script <<Initialize>>d__0.<>4__this""
IL_006b: ldfld ""int x3""
IL_0070: box ""int""
IL_0075: call ""string string.Format(string, object, object, object)""
IL_007a: call ""void System.Console.Write(string)""
IL_007f: nop
IL_0080: ldnull
IL_0081: stloc.1
IL_0082: leave.s IL_009c
}
catch System.Exception
{
IL_0084: stloc.3
IL_0085: ldarg.0
IL_0086: ldc.i4.s -2
IL_0088: stfld ""int <<Initialize>>d__0.<>1__state""
IL_008d: ldarg.0
IL_008e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_0093: ldloc.3
IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)""
IL_0099: nop
IL_009a: leave.s IL_00b1
}
IL_009c: ldarg.0
IL_009d: ldc.i4.s -2
IL_009f: stfld ""int <<Initialize>>d__0.<>1__state""
IL_00a4: ldarg.0
IL_00a5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <<Initialize>>d__0.<>t__builder""
IL_00aa: ldloc.1
IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)""
IL_00b0: nop
IL_00b1: ret
}
");
}
[Fact]
public void DeconstructionForEachInScript()
{
var source =
@"
foreach ((string x1, var (x2, x3)) in new[] { (""hello"", (42, ""world"")) })
{
System.Console.Write($""{x1} {x2} {x3}"");
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x1Symbol.Kind);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x2Symbol.Kind);
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator);
}
[Fact]
public void DeconstructionInForLoopInScript()
{
var source =
@"
for ((string x1, var (x2, x3)) = (""hello"", (42, ""world"")); ; )
{
System.Console.Write($""{x1} {x2} {x3}"");
break;
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
Assert.Equal("System.String x1", x1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x1Symbol.Kind);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
Assert.Equal("System.Int32 x2", x2Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, x2Symbol.Kind);
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "hello 42 world", sourceSymbolValidator: validator);
}
[Fact]
public void DeconstructionInCSharp6Script()
{
var source =
@"
var (x, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp6), options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,5): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x, y)").WithArguments("tuples", "7.0").WithLocation(2, 5),
// (2,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7 or greater.
// var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(2, 14)
);
}
[Fact]
public void InvalidDeconstructionInScript()
{
var source =
@"
int (x, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// int (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 5)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString());
var xType = ((IFieldSymbol)xSymbol).Type;
Assert.False(xType.IsErrorType());
Assert.Equal("System.Int32", xType.ToTestDisplayString());
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString());
var yType = ((IFieldSymbol)ySymbol).Type;
Assert.False(yType.IsErrorType());
Assert.Equal("System.Int32", yType.ToTestDisplayString());
}
[Fact]
public void InvalidDeconstructionInScript_2()
{
var source =
@"
(int (x, y), int z) = ((1, 2), 3);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,6): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// (int (x, y), int z) = ((1, 2), 3);
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x, y)").WithLocation(2, 6)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString());
var xType = ((IFieldSymbol)xSymbol).Type;
Assert.False(xType.IsErrorType());
Assert.Equal("System.Int32", xType.ToTestDisplayString());
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
Assert.Equal("System.Int32 Script.y", ySymbol.ToTestDisplayString());
var yType = ((IFieldSymbol)ySymbol).Type;
Assert.False(yType.IsErrorType());
Assert.Equal("System.Int32", yType.ToTestDisplayString());
}
[Fact]
public void NameConflictInDeconstructionInScript()
{
var source =
@"
int x1;
var (x1, x2) = (1, 2);
System.Console.Write(x1);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (3,6): error CS0102: The type 'Script' already contains a definition for 'x1'
// var (x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x1").WithArguments("Script", "x1").WithLocation(3, 6),
// (4,22): error CS0229: Ambiguity between 'x1' and 'x1'
// System.Console.Write(x1);
Diagnostic(ErrorCode.ERR_AmbigMember, "x1").WithArguments("x1", "x1").WithLocation(4, 22)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var firstX1 = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "x1").Single();
var firstX1Symbol = model.GetDeclaredSymbol(firstX1);
Assert.Equal("System.Int32 Script.x1", firstX1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, firstX1Symbol.Kind);
var secondX1 = GetDeconstructionVariable(tree, "x1");
var secondX1Symbol = model.GetDeclaredSymbol(secondX1);
Assert.Equal("System.Int32 Script.x1", secondX1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, secondX1Symbol.Kind);
Assert.NotEqual(firstX1Symbol, secondX1Symbol);
}
[Fact]
public void NameConflictInDeconstructionInScript2()
{
var source =
@"
var (x, y) = (1, 2);
var (z, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (3,9): error CS0102: The type 'Script' already contains a definition for 'y'
// var (z, y) = (1, 2);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "y").WithArguments("Script", "y").WithLocation(3, 9)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var firstY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").First();
var firstYSymbol = model.GetDeclaredSymbol(firstY);
Assert.Equal("System.Int32 Script.y", firstYSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, firstYSymbol.Kind);
var secondY = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "y").ElementAt(1);
var secondYSymbol = model.GetDeclaredSymbol(secondY);
Assert.Equal("System.Int32 Script.y", secondYSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, secondYSymbol.Kind);
Assert.NotEqual(firstYSymbol, secondYSymbol);
}
[Fact]
public void NameConflictInDeconstructionInScript3()
{
var source =
@"
var (x, (y, x)) = (1, (2, ""hello""));
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (2,13): error CS0102: The type 'Script' already contains a definition for 'x'
// var (x, (y, x)) = (1, (2, "hello"));
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("Script", "x").WithLocation(2, 13)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var firstX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").First();
var firstXSymbol = model.GetDeclaredSymbol(firstX);
Assert.Equal("System.Int32 Script.x", firstXSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, firstXSymbol.Kind);
var secondX = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == "x").ElementAt(1);
var secondXSymbol = model.GetDeclaredSymbol(secondX);
Assert.Equal("System.String Script.x", secondXSymbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, secondXSymbol.Kind);
Assert.NotEqual(firstXSymbol, secondXSymbol);
}
[Fact]
public void UnassignedUsedInDeconstructionInScript()
{
var source =
@"
System.Console.Write(x);
var (x, y) = (1, 2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "0");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
var xRef = GetReference(tree, "x");
Assert.Equal("System.Int32 Script.x", xSymbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x, xRef);
var xType = ((IFieldSymbol)xSymbol).Type;
Assert.False(xType.IsErrorType());
Assert.Equal("System.Int32", xType.ToTestDisplayString());
}
[Fact]
public void FailedInferenceInDeconstructionInScript()
{
var source =
@"
var (x, y) = (1, null);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.GetDeclarationDiagnostics().Verify(
// (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6),
// (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9)
);
comp.VerifyDiagnostics(
// (2,6): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(2, 6),
// (2,9): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'.
// var (x, y) = (1, null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(2, 9)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xSymbol = model.GetDeclaredSymbol(x);
Assert.Equal("var Script.x", xSymbol.ToTestDisplayString());
var xType = xSymbol.GetSymbol<FieldSymbol>().TypeWithAnnotations;
Assert.True(xType.Type.IsErrorType());
Assert.Equal("var", xType.ToTestDisplayString());
var xTypeISymbol = xType.Type.GetPublicSymbol();
Assert.Equal(SymbolKind.ErrorType, xTypeISymbol.Kind);
var y = GetDeconstructionVariable(tree, "y");
var ySymbol = model.GetDeclaredSymbol(y);
Assert.Equal("var Script.y", ySymbol.ToTestDisplayString());
var yType = ((IFieldSymbol)ySymbol).Type;
Assert.True(yType.IsErrorType());
Assert.Equal("var", yType.ToTestDisplayString());
}
[Fact]
public void FailedCircularInferenceInDeconstructionInScript()
{
var source =
@"
var (x1, x2) = (x2, x1);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.GetDeclarationDiagnostics().Verify(
// (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (x2, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10),
// (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (x2, x1);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x1Type = ((IFieldSymbol)x1Symbol).Type;
Assert.True(x1Type.IsErrorType());
Assert.Equal("var", x1Type.Name);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
var x2Ref = GetReference(tree, "x2");
Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x2, x2Ref);
var x2Type = ((IFieldSymbol)x2Symbol).Type;
Assert.True(x2Type.IsErrorType());
Assert.Equal("var", x2Type.Name);
}
[Fact]
public void FailedCircularInferenceInDeconstructionInScript2()
{
var source =
@"
var (x1, x2) = (y1, y2);
var (y1, y2) = (x1, x2);
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.GetDeclarationDiagnostics().Verify(
// (3,6): error CS7019: Type of 'y1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (y1, y2) = (x1, x2);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "y1").WithArguments("y1").WithLocation(3, 6),
// (2,6): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (y1, y2);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 6),
// (2,10): error CS7019: Type of 'x2' cannot be inferred since its initializer directly or indirectly refers to the definition.
// var (x1, x2) = (y1, y2);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x2").WithArguments("x2").WithLocation(2, 10)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("var Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x1Type = ((IFieldSymbol)x1Symbol).Type;
Assert.True(x1Type.IsErrorType());
Assert.Equal("var", x1Type.Name);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Symbol = model.GetDeclaredSymbol(x2);
var x2Ref = GetReference(tree, "x2");
Assert.Equal("var Script.x2", x2Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x2, x2Ref);
var x2Type = ((IFieldSymbol)x2Symbol).Type;
Assert.True(x2Type.IsErrorType());
Assert.Equal("var", x2Type.Name);
}
[Fact]
public void VarAliasInVarDeconstructionInScript()
{
var source =
@"
using var = System.Byte;
var (x1, (x2, x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (3,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// var (x1, (x2, x3)) = (1, (2, 3));
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(3, 5)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra check on var
var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x123Var.Type.ToString());
Assert.Null(model.GetTypeInfo(x123Var.Type).Type);
Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
}
[Fact]
public void VarTypeInVarDeconstructionInScript()
{
var source =
@"
class var
{
public static implicit operator var(int i) { return null; }
}
var (x1, (x2, x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics(
// (6,5): error CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// var (x1, (x2, x3)) = (1, (2, 3));
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, (x2, x3))").WithLocation(6, 5)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra check on var
var x123Var = (DeclarationExpressionSyntax)x1.Parent.Parent;
Assert.Equal("var", x123Var.Type.ToString());
Assert.Null(model.GetTypeInfo(x123Var.Type).Type);
Assert.Null(model.GetSymbolInfo(x123Var.Type).Symbol); // The var in `var (x1, x2)` has no symbol
}
[Fact]
public void VarAliasInTypedDeconstructionInScript()
{
var source =
@"
using var = System.Byte;
(var x1, (var x2, var x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2 3");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("System.Byte Script.x1", x1Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("System.Byte Script.x3", x3Symbol.ToTestDisplayString());
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra checks on x1's var
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("byte", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
var x1Alias = model.GetAliasInfo(x1Type);
Assert.Equal(SymbolKind.NamedType, x1Alias.Target.Kind);
Assert.Equal("byte", x1Alias.Target.ToDisplayString());
// extra checks on x3's var
var x3Type = GetTypeSyntax(x3);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind);
Assert.Equal("byte", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString());
var x3Alias = model.GetAliasInfo(x3Type);
Assert.Equal(SymbolKind.NamedType, x3Alias.Target.Kind);
Assert.Equal("byte", x3Alias.Target.ToDisplayString());
}
[Fact]
public void VarTypeInTypedDeconstructionInScript()
{
var source =
@"
class var
{
public static implicit operator var(int i) { return new var(); }
public override string ToString() { return ""var""; }
}
(var x1, (var x2, var x3)) = (1, (2, 3));
System.Console.Write($""{x1} {x2} {x3}"");
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "var var var");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Symbol = model.GetDeclaredSymbol(x1);
var x1Ref = GetReference(tree, "x1");
Assert.Equal("Script.var Script.x1", x1Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x1).Symbol);
VerifyModelForDeconstructionField(model, x1, x1Ref);
var x3 = GetDeconstructionVariable(tree, "x3");
var x3Symbol = model.GetDeclaredSymbol(x3);
var x3Ref = GetReference(tree, "x3");
Assert.Equal("Script.var Script.x3", x3Symbol.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(x3).Symbol);
VerifyModelForDeconstructionField(model, x3, x3Ref);
// extra checks on x1's var
var x1Type = GetTypeSyntax(x1);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x1Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x1Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x1Type));
// extra checks on x3's var
var x3Type = GetTypeSyntax(x3);
Assert.Equal(SymbolKind.NamedType, model.GetSymbolInfo(x3Type).Symbol.Kind);
Assert.Equal("var", model.GetSymbolInfo(x3Type).Symbol.ToDisplayString());
Assert.Null(model.GetAliasInfo(x3Type));
}
[Fact]
public void SimpleDiscardWithConversion()
{
var source =
@"
class C
{
static void Main()
{
(int _, var x) = (new C(1), 1);
(var _, var y) = (new C(2), 2);
var (_, z) = (new C(3), 3);
System.Console.Write($""Output {x} {y} {z}."");
}
int _i;
public C(int i) { _i = i; }
public static implicit operator int(C c) { System.Console.Write($""Converted {c._i}. ""); return 0; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "Converted 1. Output 1 2 3.");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetSymbolInfo(discard1).Symbol);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("int _", declaration1.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Null(model.GetSymbolInfo(discard2).Symbol);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("var _", declaration2.ToString());
Assert.Equal("C", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardDesignations(tree).ElementAt(2);
var declaration3 = (DeclarationExpressionSyntax)discard3.Parent.Parent;
Assert.Equal("var (_, z)", declaration3.ToString());
Assert.Equal("(C, System.Int32 z)", model.GetTypeInfo(declaration3).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration3).Symbol);
}
[Fact]
public void CannotDeconstructIntoDiscardOfWrongType()
{
var source =
@"
class C
{
static void Main()
{
(int _, string _) = (""hello"", 42);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,30): error CS0029: Cannot implicitly convert type 'string' to 'int'
// (int _, string _) = ("hello", 42);
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int").WithLocation(6, 30),
// (6,39): error CS0029: Cannot implicitly convert type 'int' to 'string'
// (int _, string _) = ("hello", 42);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(6, 39)
);
}
[Fact]
public void DiscardFromDeconstructMethod()
{
var source =
@"
class C
{
static void Main()
{
(var _, string y) = new C();
System.Console.Write(y);
}
void Deconstruct(out int x, out string y) { x = 42; y = ""hello""; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "hello");
}
[Fact]
public void ShortDiscardInDeclaration()
{
var source =
@"
class C
{
static void Main()
{
(_, var x) = (1, 2);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard = GetDiscardIdentifiers(tree).First();
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString());
var isymbol = (ISymbol)symbol;
Assert.Equal(SymbolKind.Discard, isymbol.Kind);
}
[Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")]
public void SameTypeDiscardsAreEqual01()
{
var source =
@"
class C
{
static void Main()
{
(_, _) = (1, 2);
_ = 3;
M(out _);
}
static void M(out int x) => x = 1;
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discards = GetDiscardIdentifiers(tree).ToArray();
Assert.Equal(4, discards.Length);
var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol;
Assert.Equal(symbol0, symbol0);
var set = new HashSet<ISymbol>();
foreach (var discard in discards)
{
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
set.Add(symbol);
Assert.Equal(SymbolKind.Discard, symbol.Kind);
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol0, symbol);
Assert.Equal(symbol, symbol);
Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode());
// Test to show that reference-unequal discards are equal by type.
IDiscardSymbol symbolClone = new DiscardSymbol(TypeWithAnnotations.Create(symbol.Type.GetSymbol())).GetPublicSymbol();
Assert.NotSame(symbol, symbolClone);
Assert.Equal(SymbolKind.Discard, symbolClone.Kind);
Assert.Equal("int _", symbolClone.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol.Type, symbolClone.Type);
Assert.Equal(symbol0, symbolClone);
Assert.Equal(symbol, symbolClone);
Assert.Same(symbol.Type, symbolClone.Type); // original symbol for System.Int32 has identity.
Assert.Equal(symbol.GetHashCode(), symbolClone.GetHashCode());
}
Assert.Equal(1, set.Count);
}
[Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")]
public void SameTypeDiscardsAreEqual02()
{
var source =
@"using System.Collections.Generic;
class C
{
static void Main()
{
(_, _) = (new List<int>(), new List<int>());
_ = new List<int>();
M(out _);
}
static void M(out List<int> x) => x = new List<int>();
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discards = GetDiscardIdentifiers(tree).ToArray();
Assert.Equal(4, discards.Length);
var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol;
Assert.Equal(symbol0, symbol0);
var set = new HashSet<ISymbol>();
foreach (var discard in discards)
{
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
set.Add(symbol);
Assert.Equal(SymbolKind.Discard, symbol.Kind);
Assert.Equal("List<int> _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol0, symbol);
Assert.Equal(symbol0.Type, symbol.Type);
Assert.Equal(symbol, symbol);
Assert.Equal(symbol.GetHashCode(), symbol0.GetHashCode());
if (discard != discards[0])
{
// Although it is not part of the compiler's contract, at the moment distinct constructions are distinct
Assert.NotSame(symbol.Type, symbol0.Type);
Assert.NotSame(symbol, symbol0);
}
}
Assert.Equal(1, set.Count);
}
[Fact, WorkItem(25829, "https://github.com/dotnet/roslyn/issues/25829")]
public void DifferentTypeDiscardsAreNotEqual()
{
var source =
@"
class C
{
static void Main()
{
(_, _) = (1.0, 2);
_ = 3;
M(out _);
}
static void M(out int x) => x = 1;
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discards = GetDiscardIdentifiers(tree).ToArray();
Assert.Equal(4, discards.Length);
var symbol0 = (IDiscardSymbol)model.GetSymbolInfo(discards[0]).Symbol;
var set = new HashSet<ISymbol>();
foreach (var discard in discards)
{
var symbol = (IDiscardSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal(SymbolKind.Discard, symbol.Kind);
set.Add(symbol);
if (discard == discards[0])
{
Assert.Equal("double _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal(symbol0, symbol);
Assert.Equal(symbol0.GetHashCode(), symbol.GetHashCode());
}
else
{
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.NotEqual(symbol0, symbol);
}
}
Assert.Equal(2, set.Count);
}
[Fact]
public void EscapedUnderscoreInDeclaration()
{
var source =
@"
class C
{
static void Main()
{
(@_, var x) = (1, 2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (6,10): error CS0103: The name '_' does not exist in the current context
// (@_, var x) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
Assert.Empty(GetDiscardIdentifiers(tree));
}
[Fact]
public void EscapedUnderscoreInDeclarationCSharp9()
{
var source =
@"
class C
{
static void Main()
{
(@_, var x) = (1, 2);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (@_, var x) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(@_, var x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9),
// (6,10): error CS0103: The name '_' does not exist in the current context
// (@_, var x) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "@_").WithArguments("_").WithLocation(6, 10)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
Assert.Empty(GetDiscardIdentifiers(tree));
}
[Fact]
public void UnderscoreLocalInDeconstructDeclaration()
{
var source =
@"
class C
{
static void Main()
{
int _;
(_, var x) = (1, 2);
System.Console.Write(_);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1")
.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int V_0, //_
int V_1) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldloc.0
IL_0006: call ""void System.Console.Write(int)""
IL_000b: nop
IL_000c: ret
}");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard = GetDiscardIdentifiers(tree).First();
Assert.Equal("(_, var x)", discard.Parent.Parent.ToString());
var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal("int _", symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.Int32", model.GetTypeInfo(discard).Type.ToTestDisplayString());
}
[Fact]
public void ShortDiscardInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int x;
(_, _, x) = (1, 2, 3);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "3");
}
[Fact]
public void DiscardInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int x;
(_, x) = (1L, 2);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Equal("long _", model.GetSymbolInfo(discard1).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
var tuple1 = (TupleExpressionSyntax)discard1.Parent.Parent;
Assert.Equal("(_, x)", tuple1.ToString());
Assert.Equal("(System.Int64, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(tuple1).Symbol);
}
[Fact]
public void DiscardInDeconstructDeclaration()
{
var source =
@"
class C
{
static void Main()
{
var (_, x) = (1, 2);
System.Console.Write(x);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
var tuple1 = (DeclarationExpressionSyntax)discard1.Parent.Parent;
Assert.Equal("var (_, x)", tuple1.ToString());
Assert.Equal("(System.Int32, System.Int32 x)", model.GetTypeInfo(tuple1).Type.ToTestDisplayString());
}
[Fact]
public void UnderscoreLocalInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int x, _;
(_, x) = (1, 2);
System.Console.Write($""{_} {x}"");
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard = GetDiscardIdentifiers(tree).First();
Assert.Equal("(_, x)", discard.Parent.Parent.ToString());
var symbol = (ILocalSymbol)model.GetSymbolInfo(discard).Symbol;
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
}
[Fact]
public void DiscardInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach (var (_, x) in new[] { (1, ""hello"") }) { System.Console.Write(""1 ""); }
foreach ((_, (var y, int z)) in new[] { (1, (""hello"", 2)) }) { System.Console.Write(""2""); }
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
DiscardDesignationSyntax discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Null(model.GetTypeInfo(discard1).Type);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent.Parent;
Assert.Equal("var (_, x)", declaration1.ToString());
Assert.Null(model.GetTypeInfo(discard1).Type);
Assert.Equal("(System.Int32, System.String x)", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
IdentifierNameSyntax discard2 = GetDiscardIdentifiers(tree).First();
Assert.Equal("(_, (var y, int z))", discard2.Parent.Parent.ToString());
Assert.Equal("int _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
Assert.Equal("System.Int32", model.GetTypeInfo(discard2).Type.ToTestDisplayString());
var yz = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2);
Assert.Equal("(var y, int z)", yz.ToString());
Assert.Equal("(System.String y, System.Int32 z)", model.GetTypeInfo(yz).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(yz).Symbol);
var y = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ElementAt(1);
Assert.Equal("var y", y.ToString());
Assert.Equal("System.String", model.GetTypeInfo(y).Type.ToTestDisplayString());
Assert.Equal("System.String y", model.GetSymbolInfo(y).Symbol.ToTestDisplayString());
}
[Fact]
public void TwoDiscardsInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach ((_, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2""); }
}
}
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var refs = GetReferences(tree, "_");
Assert.Equal(2, refs.Count());
model.GetTypeInfo(refs.ElementAt(0)); // Assert.Equal("int", model.GetTypeInfo(refs.ElementAt(0)).Type.ToDisplayString());
model.GetTypeInfo(refs.ElementAt(1)); // Assert.Equal("string", model.GetTypeInfo(refs.ElementAt(1)).Type.ToDisplayString());
var tuple = (TupleExpressionSyntax)refs.ElementAt(0).Parent.Parent;
Assert.Equal("(_, _)", tuple.ToString());
Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(tuple).Type.ToTestDisplayString());
};
var comp = CompileAndVerify(source, expectedOutput: @"2", sourceSymbolValidator: validator);
comp.VerifyDiagnostics(
// this is permitted now, as it is just an assignment expression
);
}
[Fact]
public void UnderscoreLocalDisallowedInForEach()
{
var source =
@"
class C
{
static void Main()
{
{
foreach ((var x, _) in new[] { (1, ""hello"") }) { System.Console.Write(""2 ""); }
}
{
int _;
foreach ((var y, _) in new[] { (1, ""hello"") }) { System.Console.Write(""4""); } // error
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (11,30): error CS0029: Cannot implicitly convert type 'string' to 'int'
// foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error
Diagnostic(ErrorCode.ERR_NoImplicitConv, "_").WithArguments("string", "int").WithLocation(11, 30),
// (11,22): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((var y, _) in new[] { (1, "hello") }) { System.Console.Write("4"); } // error
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var y, _)").WithLocation(11, 22),
// (10,17): warning CS0168: The variable '_' is declared but never used
// int _;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(10, 17)
);
}
[Fact]
public void TwoDiscardsInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
(_, _) = (new C(), new C());
}
public C() { System.Console.Write(""C""); }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "CC");
}
[Fact]
public void VerifyDiscardIL()
{
var source =
@"
class C
{
C()
{
System.Console.Write(""ctor"");
}
static int Main()
{
var (x, _, _) = (1, new C(), 2);
return x;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "ctor");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main()", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: newobj ""C..ctor()""
IL_0005: pop
IL_0006: ldc.i4.1
IL_0007: ret
}");
}
[Fact]
public void SingleDiscardInAssignment()
{
var source =
@"
class C
{
static void Main()
{
_ = M();
}
public static int M() { System.Console.Write(""M""); return 1; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "M");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardIdentifiers(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.Equal("System.Int32", model.GetTypeInfo(discard1).Type.ToTestDisplayString());
}
[Fact]
public void SingleDiscardInAssignmentInCSharp6()
{
var source =
@"
class C
{
static void Error()
{
_ = 1;
}
static void Ok()
{
int _;
_ = 1;
System.Console.Write(_);
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6);
comp.VerifyDiagnostics(
// (6,9): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater.
// _ = 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 9)
);
}
[Fact]
public void VariousDiscardsInCSharp6()
{
var source =
@"
class C
{
static void M1(out int x)
{
(_, var _, int _) = (1, 2, 3);
var (_, _) = (1, 2);
bool b = 3 is int _;
switch (3)
{
case int _:
break;
}
M1(out var _);
M1(out int _);
M1(out _);
x = 2;
}
static void M2()
{
const int _ = 3;
switch (3)
{
case _: // not a discard
break;
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6);
comp.VerifyDiagnostics(
// (6,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// (_, var _, int _) = (1, 2, 3);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, var _, int _)").WithArguments("tuples", "7.0").WithLocation(6, 9),
// (6,10): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater.
// (_, var _, int _) = (1, 2, 3);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(6, 10),
// (6,29): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// (_, var _, int _) = (1, 2, 3);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2, 3)").WithArguments("tuples", "7.0").WithLocation(6, 29),
// (7,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (_, _) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(_, _)").WithArguments("tuples", "7.0").WithLocation(7, 13),
// (7,22): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (_, _) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(1, 2)").WithArguments("tuples", "7.0").WithLocation(7, 22),
// (8,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater.
// bool b = 3 is int _;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is int _").WithArguments("pattern matching", "7.0").WithLocation(8, 18),
// (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater.
// case int _:
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case int _:").WithArguments("pattern matching", "7.0").WithLocation(11, 13),
// (14,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// M1(out var _);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(14, 20),
// (15,20): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater.
// M1(out int _);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("out variable declaration", "7.0").WithLocation(15, 20),
// (16,16): error CS8059: Feature 'discards' is not available in C# 6. Please use language version 7.0 or greater.
// M1(out _);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "_").WithArguments("discards", "7.0").WithLocation(16, 16),
// (24,18): warning CS8512: The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.
// case _: // not a discard
Diagnostic(ErrorCode.WRN_CaseConstantNamedUnderscore, "_").WithLocation(24, 18)
);
}
[Fact]
public void SingleDiscardInAsyncAssignment()
{
var source =
@"
class C
{
async void M()
{
System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // warning
_ = System.Threading.Tasks.Task.Delay(new System.TimeSpan(0)); // fire-and-forget
await System.Threading.Tasks.Task.Delay(new System.TimeSpan(0));
}
}
";
var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (6,9): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
// System.Threading.Tasks.Task.Delay(new System.TimeSpan(0));
Diagnostic(ErrorCode.WRN_UnobservedAwaitableExpression, "System.Threading.Tasks.Task.Delay(new System.TimeSpan(0))").WithLocation(6, 9)
);
}
[Fact]
public void SingleDiscardInUntypedAssignment()
{
var source =
@"
class C
{
static void Main()
{
_ = null;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,9): error CS8183: Cannot infer the type of implicitly-typed discard.
// _ = null;
Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9)
);
}
[Fact]
public void UnderscoreLocalInAssignment()
{
var source =
@"
class C
{
static void Main()
{
int _;
_ = M();
System.Console.Write(_);
}
public static int M() { return 1; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "1");
}
[Fact]
public void DeclareAndUseLocalInDeconstruction()
{
var source =
@"
class C
{
static void Main()
{
(var x, x) = (1, 2);
(y, var y) = (1, 2);
}
}
";
var compCSharp9 = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compCSharp9.VerifyDiagnostics(
// (6,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (var x, x) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(var x, x) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(6, 9),
// (6,17): error CS0841: Cannot use local variable 'x' before it is declared
// (var x, x) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17),
// (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (y, var y) = (1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(y, var y) = (1, 2)").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9),
// (7,10): error CS0841: Cannot use local variable 'y' before it is declared
// (y, var y) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10)
);
var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (6,17): error CS0841: Cannot use local variable 'x' before it is declared
// (var x, x) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 17),
// (7,10): error CS0841: Cannot use local variable 'y' before it is declared
// (y, var y) = (1, 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 10)
);
}
[Fact]
public void OutVarAndUsageInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
(M(out var x).P, x) = (1, x);
System.Console.Write(x);
}
static C M(out int i) { i = 42; return new C(); }
int P { set { System.Console.Write($""Written {value}. ""); } }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,26): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (M(out var x).P, x) = (1, x);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(6, 26)
);
CompileAndVerify(comp, expectedOutput: "Written 1. 42");
}
[Fact]
public void OutDiscardInDeconstructAssignment()
{
var source =
@"
class C
{
static void Main()
{
int _;
(M(out var _).P, _) = (1, 2);
System.Console.Write(_);
}
static C M(out int i) { i = 42; return new C(); }
int P { set { System.Console.Write($""Written {value}. ""); } }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "Written 1. 2");
}
[Fact]
public void OutDiscardInDeconstructTarget()
{
var source =
@"
class C
{
static void Main()
{
(x, _) = (M(out var x), 2);
System.Console.Write(x);
}
static int M(out int i) { i = 42; return 3; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,10): error CS0841: Cannot use local variable 'x' before it is declared
// (x, _) = (M(out var x), 2);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 10)
);
}
[Fact]
public void SimpleDiscardDeconstructInScript()
{
var source =
@"
using alias = System.Int32;
(string _, alias _) = (""hello"", 42);
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("string _", declaration1.ToString());
Assert.Null(model.GetDeclaredSymbol(declaration1));
Assert.Null(model.GetDeclaredSymbol(discard1));
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("alias _", declaration2.ToString());
Assert.Null(model.GetDeclaredSymbol(declaration2));
Assert.Null(model.GetDeclaredSymbol(discard2));
var tuple = (TupleExpressionSyntax)declaration1.Parent.Parent;
Assert.Equal("(string _, alias _)", tuple.ToString());
Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(tuple).Type.ToTestDisplayString());
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, sourceSymbolValidator: validator);
}
[Fact]
public void SimpleDiscardDeconstructInScript2()
{
var source =
@"
public class C
{
public C() { System.Console.Write(""ctor""); }
public void Deconstruct(out string x, out string y) { x = y = null; }
}
(string _, string _) = new C();
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor");
}
[Fact]
public void SingleDiscardInAssignmentInScript()
{
var source =
@"
int M() { System.Console.Write(""M""); return 1; }
_ = M();
";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "M");
}
[Fact]
public void NestedVarDiscardDeconstructionInScript()
{
var source =
@"
(var _, var (_, x3)) = (""hello"", (42, 43));
System.Console.Write($""{x3}"");
";
Action<ModuleSymbol> validator = (ModuleSymbol module) =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
var nestedDeclaration = (DeclarationExpressionSyntax)discard2.Parent.Parent;
Assert.Equal("var (_, x3)", nestedDeclaration.ToString());
Assert.Null(model.GetDeclaredSymbol(nestedDeclaration));
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.Equal("(System.Int32, System.Int32 x3)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol);
var tuple = (TupleExpressionSyntax)discard2.Parent.Parent.Parent.Parent;
Assert.Equal("(var _, var (_, x3))", tuple.ToString());
Assert.Equal("(System.String, (System.Int32, System.Int32 x3))", model.GetTypeInfo(tuple).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(tuple).Symbol);
};
var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe, references: s_valueTupleRefs);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "43", sourceSymbolValidator: validator);
}
[Fact]
public void VariousDiscardsInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach ((var _, int _, _, var (_, _), int x) in new[] { (1L, 2, 3, (""hello"", 5), 6) })
{
System.Console.Write(x);
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "6");
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var discard1 = GetDiscardDesignations(tree).First();
Assert.Null(model.GetDeclaredSymbol(discard1));
Assert.True(model.GetSymbolInfo(discard1).IsEmpty);
Assert.Null(model.GetTypeInfo(discard1).Type);
var declaration1 = (DeclarationExpressionSyntax)discard1.Parent;
Assert.Equal("var _", declaration1.ToString());
Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration1).Symbol);
var discard2 = GetDiscardDesignations(tree).ElementAt(1);
Assert.Null(model.GetDeclaredSymbol(discard2));
Assert.True(model.GetSymbolInfo(discard2).IsEmpty);
Assert.Null(model.GetTypeInfo(discard2).Type);
var declaration2 = (DeclarationExpressionSyntax)discard2.Parent;
Assert.Equal("int _", declaration2.ToString());
Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(declaration2).Symbol);
var discard3 = GetDiscardIdentifiers(tree).First();
Assert.Equal("_", discard3.Parent.ToString());
Assert.Null(model.GetDeclaredSymbol(discard3));
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
Assert.Equal("int _", model.GetSymbolInfo(discard3).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol;
Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString());
Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString());
var discard4 = GetDiscardDesignations(tree).ElementAt(2);
Assert.Null(model.GetDeclaredSymbol(discard4));
Assert.True(model.GetSymbolInfo(discard4).IsEmpty);
Assert.Null(model.GetTypeInfo(discard4).Type);
var nestedDeclaration = (DeclarationExpressionSyntax)discard4.Parent.Parent;
Assert.Equal("var (_, _)", nestedDeclaration.ToString());
Assert.Equal("(System.String, System.Int32)", model.GetTypeInfo(nestedDeclaration).Type.ToTestDisplayString());
Assert.Null(model.GetSymbolInfo(nestedDeclaration).Symbol);
}
[Fact]
public void UnderscoreInCSharp6Foreach()
{
var source =
@"
class C
{
static void Main()
{
foreach (var _ in M())
{
System.Console.Write(_);
}
}
static System.Collections.Generic.IEnumerable<int> M()
{
System.Console.Write(""M "");
yield return 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "M 1");
}
[Fact]
public void ShortDiscardDisallowedInForeach()
{
var source =
@"
class C
{
static void Main()
{
foreach (_ in M())
{
}
}
static System.Collections.Generic.IEnumerable<int> M()
{
yield return 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach (_ in M())
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "_").WithLocation(6, 18)
);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var discard = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().First();
var symbol = (DiscardSymbol)model.GetSymbolInfo(discard).Symbol.GetSymbol();
Assert.True(symbol.TypeWithAnnotations.Type.IsErrorType());
}
[Fact]
public void ExistingUnderscoreLocalInLegacyForeach()
{
var source =
@"
class C
{
static void Main()
{
int _;
foreach (var _ in new[] { 1 })
{
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,22): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// foreach (var _ in new[] { 1 })
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(7, 22),
// (6,13): warning CS0168: The variable '_' is declared but never used
// int _;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 13)
);
}
[Fact]
public void MixedDeconstruction_01()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
var x = (int x1, int x2) = t;
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics(
// (7,18): error CS8185: A declaration is not allowed in this context.
// var x = (int x1, int x2) = t;
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 18)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2, x2Ref);
}
[Fact]
public void MixedDeconstruction_02()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
int z;
(int x1, z) = t;
System.Console.WriteLine(x1);
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "1")
.VerifyIL("Program.Main", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (System.ValueTuple<int, int> V_0, //t
int V_1, //z
int V_2) //x1
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.0
IL_000b: dup
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: stloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0017: stloc.1
IL_0018: ldloc.2
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: nop
IL_001f: ret
}");
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
}
[Fact]
public void MixedDeconstruction_03()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
int z;
for ((int x1, z) = t; ; )
{
System.Console.WriteLine(x1);
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "1")
.VerifyIL("Program.Main", @"
{
// Code size 39 (0x27)
.maxstack 3
.locals init (System.ValueTuple<int, int> V_0, //t
int V_1, //z
int V_2) //x1
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.0
IL_000b: dup
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: stloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0017: stloc.1
IL_0018: br.s IL_0024
IL_001a: nop
IL_001b: ldloc.2
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: nop
IL_0022: br.s IL_0026
IL_0024: br.s IL_001a
IL_0026: ret
}");
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
var symbolInfo = model.GetSymbolInfo(x1Ref);
Assert.Equal(symbolInfo.Symbol, model.GetDeclaredSymbol(x1));
Assert.Equal(SpecialType.System_Int32, symbolInfo.Symbol.GetTypeOrReturnType().SpecialType);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(1);
Assert.Equal(@"(int x1, z)", lhs.ToString());
Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x1, System.Int32 z)", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
}
[Fact]
public void MixedDeconstruction_03CSharp9()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
int z;
for ((int x1, z) = t; ; )
{
System.Console.WriteLine(x1);
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (8,14): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// for ((int x1, z) = t; ; )
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x1, z) = t").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(8, 14));
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1, x1Ref);
}
[Fact]
public void MixedDeconstruction_04()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, 2);
for (; ; (int x1, int x2) = t)
{
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,19): error CS8185: A declaration is not allowed in this context.
// for (; ; (int x1, int x2) = t)
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(7, 19),
// (9,38): error CS0103: The name 'x1' does not exist in the current context
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(9, 38),
// (10,38): error CS0103: The name 'x2' does not exist in the current context
// System.Console.WriteLine(x2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(10, 38)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
VerifyModelForDeconstructionLocal(model, x1);
var symbolInfo = model.GetSymbolInfo(x1Ref);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
VerifyModelForDeconstructionLocal(model, x2);
symbolInfo = model.GetSymbolInfo(x2Ref);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
}
[Fact]
public void MixedDeconstruction_05()
{
string source = @"
class Program
{
static void Main(string[] args)
{
foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
{
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
static int _M;
static ref int M(out int x) { x = 2; return ref _M; }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,34): error CS0131: The left-hand side of an assignment must be a variable, property or indexer
// foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "args is var x2").WithLocation(6, 34),
// (6,34): error CS0029: Cannot implicitly convert type 'int' to 'bool'
// foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
Diagnostic(ErrorCode.ERR_NoImplicitConv, "args is var x2").WithArguments("int", "bool").WithLocation(6, 34),
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((M(out var x1), args is var x2, _) in new[] { (1, 2, 3) })
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(M(out var x1), args is var x2, _)").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString());
model = compilation.GetSemanticModel(tree);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.Equal("string[]", model.GetTypeInfo(x2Ref).Type.ToDisplayString());
VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref);
VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref);
}
[Fact]
public void ForeachIntoExpression()
{
string source = @"
class Program
{
static void Main(string[] args)
{
foreach (M(out var x1) in new[] { 1, 2, 3 })
{
System.Console.WriteLine(x1);
}
}
static int _M;
static ref int M(out int x) { x = 2; return ref _M; }
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,32): error CS0230: Type and identifier are both required in a foreach statement
// foreach (M(out var x1) in new[] { 1, 2, 3 })
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 32)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString());
VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref);
}
[Fact]
public void MixedDeconstruction_06()
{
string source = @"
class Program
{
static void Main(string[] args)
{
foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3})
{
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
static int _M;
static ref int M1(int m2, int x, string[] y) { return ref _M; }
static int M2(out int x, bool b) => x = 2;
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,61): error CS0230: Type and identifier are both required in a foreach statement
// foreach (M1(M2(out var x1, args is var x2), x1, x2) in new[] {1, 2, 3})
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(6, 61)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReferences(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref.First()).Type.ToDisplayString());
model = compilation.GetSemanticModel(tree);
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReferences(tree, "x2");
Assert.Equal("string[]", model.GetTypeInfo(x2Ref.First()).Type.ToDisplayString());
VerifyModelForLocal(model, x1, LocalDeclarationKind.OutVariable, x1Ref.ToArray());
VerifyModelForLocal(model, x2, LocalDeclarationKind.PatternVariable, x2Ref.ToArray());
}
[Fact]
public void MixedDeconstruction_07()
{
string source = @"
class Program
{
static void Main(string[] args)
{
var t = (1, ("""", true));
string y;
for ((int x, (y, var z)) = t; ; )
{
System.Console.Write(x);
System.Console.Write(z);
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
CompileAndVerify(compilation, expectedOutput: "1True")
.VerifyIL("Program.Main", @"
{
// Code size 73 (0x49)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<string, bool>> V_0, //t
string V_1, //y
int V_2, //x
bool V_3, //z
System.ValueTuple<string, bool> V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldstr """"
IL_0009: ldc.i4.1
IL_000a: newobj ""System.ValueTuple<string, bool>..ctor(string, bool)""
IL_000f: call ""System.ValueTuple<int, System.ValueTuple<string, bool>>..ctor(int, System.ValueTuple<string, bool>)""
IL_0014: ldloc.0
IL_0015: dup
IL_0016: ldfld ""System.ValueTuple<string, bool> System.ValueTuple<int, System.ValueTuple<string, bool>>.Item2""
IL_001b: stloc.s V_4
IL_001d: ldfld ""int System.ValueTuple<int, System.ValueTuple<string, bool>>.Item1""
IL_0022: stloc.2
IL_0023: ldloc.s V_4
IL_0025: ldfld ""string System.ValueTuple<string, bool>.Item1""
IL_002a: stloc.1
IL_002b: ldloc.s V_4
IL_002d: ldfld ""bool System.ValueTuple<string, bool>.Item2""
IL_0032: stloc.3
IL_0033: br.s IL_0046
IL_0035: nop
IL_0036: ldloc.2
IL_0037: call ""void System.Console.Write(int)""
IL_003c: nop
IL_003d: ldloc.3
IL_003e: call ""void System.Console.Write(bool)""
IL_0043: nop
IL_0044: br.s IL_0048
IL_0046: br.s IL_0035
IL_0048: ret
}");
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x = GetDeconstructionVariable(tree, "x");
var xRef = GetReference(tree, "x");
VerifyModelForDeconstructionLocal(model, x, xRef);
var xSymbolInfo = model.GetSymbolInfo(xRef);
Assert.Equal(xSymbolInfo.Symbol, model.GetDeclaredSymbol(x));
Assert.Equal(SpecialType.System_Int32, xSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType);
var z = GetDeconstructionVariable(tree, "z");
var zRef = GetReference(tree, "z");
VerifyModelForDeconstructionLocal(model, z, zRef);
var zSymbolInfo = model.GetSymbolInfo(zRef);
Assert.Equal(zSymbolInfo.Symbol, model.GetDeclaredSymbol(z));
Assert.Equal(SpecialType.System_Boolean, zSymbolInfo.Symbol.GetTypeOrReturnType().SpecialType);
var lhs = tree.GetRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ElementAt(2);
Assert.Equal(@"(int x, (y, var z))", lhs.ToString());
Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).Type.ToTestDisplayString());
Assert.Equal("(System.Int32 x, (System.String y, System.Boolean z))", model.GetTypeInfo(lhs).ConvertedType.ToTestDisplayString());
}
[Fact]
public void IncompleteDeclarationIsSeenAsTupleLiteral()
{
string source = @"
class C
{
static void Main()
{
(int x1, string x2);
System.Console.WriteLine(x1);
System.Console.WriteLine(x2);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 10),
// (6,18): error CS8185: A declaration is not allowed in this context.
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string x2").WithLocation(6, 18),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x1, string x2)").WithLocation(6, 9),
// (6,10): error CS0165: Use of unassigned local variable 'x1'
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 10),
// (6,18): error CS0165: Use of unassigned local variable 'x2'
// (int x1, string x2);
Diagnostic(ErrorCode.ERR_UseDefViolation, "string x2").WithArguments("x2").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var x1 = GetDeconstructionVariable(tree, "x1");
var x1Ref = GetReference(tree, "x1");
Assert.Equal("int", model.GetTypeInfo(x1Ref).Type.ToDisplayString());
var x2 = GetDeconstructionVariable(tree, "x2");
var x2Ref = GetReference(tree, "x2");
Assert.Equal("string", model.GetTypeInfo(x2Ref).Type.ToDisplayString());
VerifyModelForDeconstruction(model, x1, LocalDeclarationKind.DeclarationExpressionVariable, x1Ref);
VerifyModelForDeconstruction(model, x2, LocalDeclarationKind.DeclarationExpressionVariable, x2Ref);
}
[Fact]
[WorkItem(15893, "https://github.com/dotnet/roslyn/issues/15893")]
public void DeconstructionOfOnlyOneElement()
{
string source = @"
class C
{
static void Main()
{
var (p2) = (1, 2);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,16): error CS1003: Syntax error, ',' expected
// var (p2) = (1, 2);
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(",", ")").WithLocation(6, 16),
// (6,16): error CS1001: Identifier expected
// var (p2) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 16)
);
}
[Fact]
[WorkItem(14876, "https://github.com/dotnet/roslyn/issues/14876")]
public void TupleTypeInDeconstruction()
{
string source = @"
class C
{
static void Main()
{
(int x, (string, long) y) = M();
System.Console.Write($""{x} {y}"");
}
static (int, (string, long)) M()
{
return (5, (""Goo"", 34983490));
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "5 (Goo, 34983490)");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")]
public void RefReturningVarInvocation()
{
string source = @"
class C
{
static int i;
static void Main()
{
int x = 0, y = 0;
(var(x, y)) = 42; // parsed as invocation
System.Console.Write(i);
}
static ref int var(int a, int b) { return ref i; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "42", verify: Verification.Passes);
comp.VerifyDiagnostics();
}
[Fact]
void InvokeVarForLvalueInParens()
{
var source = @"
class Program
{
public static void Main()
{
(var(x, y)) = 10;
System.Console.WriteLine(z);
}
static int x = 1, y = 2, z = 3;
static ref int var(int x, int y)
{
return ref z;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
// PEVerify fails with ref return https://github.com/dotnet/roslyn/issues/12285
CompileAndVerify(compilation, expectedOutput: "10", verify: Verification.Fails);
}
[Fact]
[WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")]
public void DefAssignmentsStruct001()
{
string source = @"
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
((int, int), string)[] arr = new((int, int), string)[1];
Test5(arr);
}
public static void Test4(IEnumerable<(KeyValuePair<int, int>, string)> en)
{
foreach ((KeyValuePair<int, int> kv, string s) in en)
{
var a = kv.Key; // false error CS0170: Use of possibly unassigned field
}
}
public static void Test5(IEnumerable<((int, int), string)> en)
{
foreach (((int, int k) t, string s) in en)
{
var a = t.k; // false error CS0170: Use of possibly unassigned field
System.Console.WriteLine(a);
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "0");
}
[Fact]
[WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")]
public void DefAssignmentsStruct002()
{
string source = @"
public class MyClass
{
public static void Main()
{
var data = new int[10];
var arr = new int[2];
foreach (arr[out int size] in data) {}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (9,36): error CS0230: Type and identifier are both required in a foreach statement
// foreach (arr[out int size] in data) {}
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(9, 36)
);
}
[Fact]
[WorkItem(16106, "https://github.com/dotnet/roslyn/issues/16106")]
public void DefAssignmentsStruct003()
{
string source = @"
public class MyClass
{
public static void Main()
{
var data = new (int, int)[10];
var arr = new int[2];
foreach ((arr[out int size], int b) in data) {}
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (9,27): error CS1615: Argument 1 may not be passed with the 'out' keyword
// foreach ((arr[out int size], int b) in data) {}
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int size").WithArguments("1", "out").WithLocation(9, 27),
// (9,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((arr[out int size], int b) in data) {}
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(arr[out int size], int b)").WithLocation(9, 18)
);
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_01()
{
string source = @"
class C
{
static event System.Action E;
static void Main()
{
(E, _) = (null, 1);
System.Console.WriteLine(E == null);
(E, _) = (Handler, 1);
E();
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput:
@"True
Handler");
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_02()
{
string source = @"
struct S
{
event System.Action E;
class C
{
static void Main()
{
var s = new S();
(s.E, _) = (null, 1);
System.Console.WriteLine(s.E == null);
(s.E, _) = (Handler, 1);
s.E();
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
}
";
var comp = CompileAndVerify(source, expectedOutput:
@"True
Handler");
comp.VerifyDiagnostics();
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_03()
{
string source1 = @"
public interface EventInterface
{
event System.Action E;
}
";
var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular);
string source2 = @"
class C : EventInterface
{
public event System.Action E;
static void Main()
{
var c = new C();
c.Test();
}
void Test()
{
(E, _) = (null, 1);
System.Console.WriteLine(E == null);
(E, _) = (Handler, 1);
E();
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
";
var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput:
@"True
Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() }));
comp2.VerifyDiagnostics();
Assert.True(comp2.Compilation.GetMember<IEventSymbol>("C.E").IsWindowsRuntimeEvent);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.WinRTNeedsWindowsDesktop)]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_04()
{
string source1 = @"
public interface EventInterface
{
event System.Action E;
}
";
var comp1 = CreateEmptyCompilation(source1, WinRtRefs, TestOptions.ReleaseWinMD, TestOptions.Regular);
string source2 = @"
struct S : EventInterface
{
public event System.Action E;
class C
{
S s = new S();
static void Main()
{
var c = new C();
(GetC(c).s.E, _) = (null, GetInt(1));
System.Console.WriteLine(c.s.E == null);
(GetC(c).s.E, _) = (Handler, GetInt(2));
c.s.E();
}
static int GetInt(int i)
{
System.Console.WriteLine(i);
return i;
}
static C GetC(C c)
{
System.Console.WriteLine(""GetC"");
return c;
}
static void Handler()
{
System.Console.WriteLine(""Handler"");
}
}
}
";
var comp2 = CompileAndVerify(source2, targetFramework: TargetFramework.Empty, expectedOutput:
@"GetC
1
True
GetC
2
Handler", references: WinRtRefs.Concat(new[] { ValueTupleRef, comp1.ToMetadataReference() }));
comp2.VerifyDiagnostics();
Assert.True(comp2.Compilation.GetMember<IEventSymbol>("S.E").IsWindowsRuntimeEvent);
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_05()
{
string source = @"
class C
{
public static event System.Action E;
}
class Program
{
static void Main()
{
(C.E, _) = (null, 1);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (11,12): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C')
// (C.E, _) = (null, 1);
Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 12)
);
}
[Fact]
[WorkItem(16962, "https://github.com/dotnet/roslyn/issues/16962")]
public void Events_06()
{
string source = @"
class C
{
static event System.Action E
{
add {}
remove {}
}
static void Main()
{
(E, _) = (null, 1);
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (12,10): error CS0079: The event 'C.E' can only appear on the left hand side of += or -=
// (E, _) = (null, 1);
Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "E").WithArguments("C.E").WithLocation(12, 10)
);
}
[Fact]
public void SimpleAssignInConstructor()
{
string source = @"
public class C
{
public long x;
public string y;
public C(int a, string b) => (x, y) = (a, b);
public static void Main()
{
var c = new C(1, ""hello"");
System.Console.WriteLine(c.x + "" "" + c.y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C..ctor(int, string)", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (long V_0,
string V_1)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.1
IL_0007: conv.i8
IL_0008: stloc.0
IL_0009: ldarg.2
IL_000a: stloc.1
IL_000b: ldarg.0
IL_000c: ldloc.0
IL_000d: stfld ""long C.x""
IL_0012: ldarg.0
IL_0013: ldloc.1
IL_0014: stfld ""string C.y""
IL_0019: ret
}");
}
[Fact]
public void DeconstructAssignInConstructor()
{
string source = @"
public class C
{
public long x;
public string y;
public C(C oldC) => (x, y) = oldC;
public C() { }
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
public static void Main()
{
var oldC = new C() { x = 1, y = ""hello"" };
var newC = new C(oldC);
System.Console.WriteLine(newC.x + "" "" + newC.y);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C..ctor(C)", @"
{
// Code size 34 (0x22)
.maxstack 3
.locals init (int V_0,
string V_1,
long V_2)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.1
IL_0007: ldloca.s V_0
IL_0009: ldloca.s V_1
IL_000b: callvirt ""void C.Deconstruct(out int, out string)""
IL_0010: ldloc.0
IL_0011: conv.i8
IL_0012: stloc.2
IL_0013: ldarg.0
IL_0014: ldloc.2
IL_0015: stfld ""long C.x""
IL_001a: ldarg.0
IL_001b: ldloc.1
IL_001c: stfld ""string C.y""
IL_0021: ret
}");
}
[Fact]
public void AssignInConstructorWithProperties()
{
string source = @"
public class C
{
public long X { get; set; }
public string Y { get; }
private int z;
public ref int Z { get { return ref z; } }
public C(int a, string b, ref int c) => (X, Y, Z) = (a, b, c);
public static void Main()
{
int number = 2;
var c = new C(1, ""hello"", ref number);
System.Console.WriteLine($""{c.X} {c.Y} {c.Z}"");
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "1 hello 2");
comp.VerifyDiagnostics();
comp.VerifyIL("C..ctor(int, string, ref int)", @"
{
// Code size 39 (0x27)
.maxstack 4
.locals init (long V_0,
string V_1,
int V_2,
long V_3)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: call ""ref int C.Z.get""
IL_000c: ldarg.1
IL_000d: conv.i8
IL_000e: stloc.0
IL_000f: ldarg.2
IL_0010: stloc.1
IL_0011: ldarg.3
IL_0012: ldind.i4
IL_0013: stloc.2
IL_0014: ldarg.0
IL_0015: ldloc.0
IL_0016: dup
IL_0017: stloc.3
IL_0018: call ""void C.X.set""
IL_001d: ldarg.0
IL_001e: ldloc.1
IL_001f: stfld ""string C.<Y>k__BackingField""
IL_0024: ldloc.2
IL_0025: stind.i4
IL_0026: ret
}");
}
[Fact]
public void VerifyDeconstructionInAsync()
{
var source =
@"
using System.Threading.Tasks;
class C
{
static void Main()
{
System.Console.Write(C.M().Result);
}
static async Task<int> M()
{
await Task.Delay(0);
var (x, y) = (1, 2);
return x + y;
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "3");
}
[Fact]
public void DeconstructionWarnsForSelfAssignment()
{
var source =
@"
class C
{
object x = 1;
static object y = 2;
void M()
{
((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,11): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// ((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 11),
// (8,18): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// ((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "this.x").WithLocation(8, 18),
// (8,26): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// ((x, x), this.x, C.y) = ((x, (1, 2)), x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "C.y").WithLocation(8, 26)
);
}
[Fact]
public void DeconstructionWarnsForSelfAssignment2()
{
var source =
@"
class C
{
object x = 1;
static object y = 2;
void M()
{
object z = 3;
(x, (y, z)) = (x, (y, z));
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, (y, z));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x"),
// (9,14): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, (y, z));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y").WithLocation(9, 14),
// (9,17): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, (y, z));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "z").WithLocation(9, 17)
);
}
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithUserDefinedConversionOnElement()
{
var source =
@"
class C
{
object x = 1;
static C y = null;
void M()
{
(x, y) = (x, (C)(D)y);
}
public static implicit operator C(D d) => null;
}
class D
{
public static implicit operator D(C c) => null;
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (8,10): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, y) = (x, (C)(D)y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(8, 10)
);
}
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithNestedConversions()
{
var source =
@"
class C
{
object x = 1;
int y = 2;
byte b = 3;
void M()
{
// The conversions on the right-hand-side:
// - a deconstruction conversion
// - an implicit tuple literal conversion on the entire right-hand-side
// - another implicit tuple literal conversion on the nested tuple
// - a conversion on element `b`
(_, (x, y)) = (1, (x, b));
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (14,14): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (_, (x, y)) = (1, (x, b));
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(14, 14)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithExplicitTupleConversion()
{
var source =
@"
class C
{
int y = 2;
byte b = 3;
void M()
{
// The conversions on the right-hand-side:
// - a deconstruction conversion on the entire right-hand-side
// - an identity conversion as its operand
// - an explicit tuple literal conversion as its operand
(y, _) = ((int, int))(y, b);
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
);
var tree = comp.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
Assert.Equal("((int, int))(y, b)", node.ToString());
comp.VerifyOperationTree(node, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(y, b)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 b)) (Syntax: '(y, b)')
NaturalType: (System.Int32 y, System.Byte b)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.Int32 C.y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'y')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'b')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.Byte C.b (OperationKind.FieldReference, Type: System.Byte) (Syntax: 'b')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'b')
");
}
[Fact]
public void DeconstructionWarnsForSelfAssignment_WithDeconstruct()
{
var source =
@"
class C
{
object x = 1;
static object y = 2;
void M()
{
object z = 3;
(x, (y, z)) = (x, y);
}
}
static class Extensions
{
public static void Deconstruct(this object input, out object output1, out object output2)
{
output1 = input;
output2 = input;
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: s_valueTupleRefs, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (9,10): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// (x, (y, z)) = (x, y);
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "x").WithLocation(9, 10)
);
}
[Fact]
public void TestDeconstructOnErrorType()
{
var source =
@"
class C
{
Error M()
{
int x, y;
(x, y) = M();
throw null;
}
}";
var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); // no ValueTuple reference
comp.VerifyDiagnostics(
// (4,5): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// Error M()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 5)
);
}
[Fact]
public void TestDeconstructOnErrorTypeFromImageReference()
{
var missing_cs = "public class Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = "public class C { public Missing M() { throw null; } }";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll);
var source =
@"
class D
{
void M()
{
int x, y;
(x, y) = new C().M();
throw null;
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.DebugDll); // no ValueTuple reference
comp.VerifyDiagnostics(
// (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// (x, y) = new C().M();
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18)
);
}
[Fact]
public void TestDeconstructOnErrorTypeFromCompilationReference()
{
var missing_cs = "public class Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = "public class C { public Missing M() { throw null; } }";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.ToMetadataReference() }, options: TestOptions.DebugDll);
var source =
@"
class D
{
void M()
{
int x, y;
(x, y) = new C().M();
throw null;
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.ToMetadataReference() }, options: TestOptions.DebugDll); // no ValueTuple reference
comp.VerifyDiagnostics(
// (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// (x, y) = new C().M();
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C().M").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18)
);
}
[Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")]
public void TestDiscardedAssignmentNotLvalue()
{
var source = @"
class Program
{
struct S1
{
public int field;
public int Increment() => field++;
}
static void Main()
{
S1 v = default(S1);
v.Increment();
(_ = v).Increment();
System.Console.WriteLine(v.field);
}
}
";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction()
{
var source = @"
class C
{
static void Main()
{
var t = (1, 2);
var (a, b) = ((byte, byte))t;
System.Console.Write($""{a} {b}"");
}
}";
CompileAndVerify(source, expectedOutput: @"1 2");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction2()
{
var source = @"
class C
{
static void Main()
{
var t = (new C(), new D());
var (a, _) = ((byte, byte))t;
System.Console.Write($""{a}"");
}
public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; }
}
class D
{
public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; }
}";
CompileAndVerify(source, expectedOutput: @"Convert Convert2 1");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction3()
{
var source = @"
class C
{
static int A { set { System.Console.Write(""A ""); } }
static int B { set { System.Console.Write(""B""); } }
static void Main()
{
(A, B) = ((byte, byte))(new C(), new D());
}
public static explicit operator byte(C c) { System.Console.Write(""Convert ""); return 1; }
public C() { System.Console.Write(""C ""); }
}
class D
{
public static explicit operator byte(D c) { System.Console.Write(""Convert2 ""); return 2; }
public D() { System.Console.Write(""D ""); }
}";
var compilation = CompileAndVerify(source, expectedOutput: @"C Convert D Convert2 A B").Compilation;
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
Assert.Equal("((byte, byte))(new C(), new D())", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.Byte)) (Syntax: '((byte, byt ... ), new D())')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Byte, System.Byte)) (Syntax: '(new C(), new D())')
NaturalType: (C, D)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte C.op_Explicit(C c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new C()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte C.op_Explicit(C c))
Operand:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Byte D.op_Explicit(D c)) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'new D()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Byte D.op_Explicit(D c))
Operand:
IObjectCreationOperation (Constructor: D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'new D()')
Arguments(0)
Initializer:
null
");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void TupleCastInDeconstruction4()
{
var source = @"
class C
{
static void Main()
{
var (a, _) = ((short, short))((int, int))(1L, 2L);
System.Console.Write($""{a}"");
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"1").Compilation;
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().ElementAt(1);
Assert.Equal("((int, int))(1L, 2L)", node.ToString());
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L')
");
Assert.Equal("((short, short))((int, int))(1L, 2L)", node.Parent.ToString());
compilation.VerifyOperationTree(node.Parent, expectedOperationTree:
@"
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int16, System.Int16)) (Syntax: '((short, sh ... t))(1L, 2L)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32)) (Syntax: '((int, int))(1L, 2L)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1L, 2L)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1) (Syntax: '1L')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2L')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 2) (Syntax: '2L')
");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void UserDefinedCastInDeconstruction()
{
var source = @"
class C
{
static void Main()
{
var c = new C();
var (a, b) = ((byte, byte))c;
System.Console.Write($""{a} {b}"");
}
public static explicit operator (byte, byte)(C c)
{
return (3, 4);
}
}";
CompileAndVerify(source, expectedOutput: @"3 4");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void DeconstructionLoweredToNothing()
{
var source = @"
class C
{
static void M()
{
for (var(_, _) = (1, 2); ; (_, _) = (3, 4))
{
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("C.M", @"
{
// Code size 2 (0x2)
.maxstack 0
IL_0000: br.s IL_0000
}");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void DeconstructionLoweredToNothing2()
{
var source = @"
class C
{
static void M()
{
(_, _) = (1, 2);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp);
verifier.VerifyIL("C.M", @"
{
// Code size 1 (0x1)
.maxstack 0
IL_0000: ret
}");
}
[Fact, WorkItem(19398, "https://github.com/dotnet/roslyn/issues/19398")]
public void DeconstructionLoweredToNothing3()
{
var source = @"
class C
{
static void Main()
{
foreach (var(_, _) in new[] { (1, 2) })
{
System.Console.Write(""once"");
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "once");
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName()
{
var source =
@"class C
{
static void Main()
{
int x = 0, y = 1;
var t = (x, y);
var (a, b) = t;
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ConditionalOperator()
{
var source =
@"class C
{
static void M(int a, int b, bool c)
{
(var x, var y) = c ? (a, default(object)) : (b, null);
(x, y) = c ? (a, default(string)) : (b, default(object));
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ImplicitArray()
{
var source =
@"class C
{
static void M(int x)
{
int y;
object z;
(y, z) = (new [] { (x, default(object)), (2, 3) })[0];
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")]
public void InferredName_Lambda()
{
// See https://github.com/dotnet/roslyn/issues/32006
// need to relax assertion in GetImplicitTupleLiteralConversion
var source =
@"class C
{
static T F<T>(System.Func<object, bool, T> f)
{
return f(null, false);
}
static void M()
{
var (x, y) = F((a, b) =>
{
if (b) return (default(object), a);
return (null, null);
});
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ConditionalOperator_LongTuple()
{
var source =
@"class C
{
static void M(object a, object b, bool c)
{
var (_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) = c ?
(1, 2, 3, 4, 5, 6, 7, a, b, 10) :
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
}";
// C# 7.0
var comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics();
// C# 7.1
comp = CreateCompilation(
source,
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics();
}
[WorkItem(21028, "https://github.com/dotnet/roslyn/issues/21028")]
[Fact]
public void InferredName_ConditionalOperator_UseSite()
{
var source =
@"class C
{
static void M(int a, int b, bool c)
{
var (x, y) = c ? ((object)1, a) : (b, 2);
}
}
namespace System
{
struct ValueTuple<T1, T2>
{
public T1 Item1;
private T2 Item2;
public ValueTuple(T1 item1, T2 item2) => throw null;
}
}";
var expected = new[] {
// (12,19): warning CS0649: Field '(T1, T2).Item1' is never assigned to, and will always have its default value
// public T1 Item1;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item1").WithArguments("(T1, T2).Item1", "").WithLocation(12, 19),
// (13,20): warning CS0169: The field '(T1, T2).Item2' is never used
// private T2 Item2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20)
};
// C# 7.0
var comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics(expected);
// C# 7.1
comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics(expected);
}
[Fact]
public void InferredName_ConditionalOperator_UseSite_AccessingWithinConstructor()
{
var source =
@"class C
{
static void M(int a, int b, bool c)
{
var (x, y) = c ? ((object)1, a) : (b, 2);
}
}
namespace System
{
struct ValueTuple<T1, T2>
{
public T1 Item1;
private T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
}
}";
var expected = new[]
{
// (13,20): warning CS0169: The field '(T1, T2).Item2' is never used
// private T2 Item2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Item2").WithArguments("(T1, T2).Item2").WithLocation(13, 20),
// (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller
// public ValueTuple(T1 item1, T2 item2)
Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16),
// (14,16): error CS0171: Field '(T1, T2).Item2' must be fully assigned before control is returned to the caller
// public ValueTuple(T1 item1, T2 item2)
Diagnostic(ErrorCode.ERR_UnassignedThis, "ValueTuple").WithArguments("(T1, T2).Item2").WithLocation(14, 16),
// (17,13): error CS0229: Ambiguity between '(T1, T2).Item2' and '(T1, T2).Item2'
// Item2 = item2;
Diagnostic(ErrorCode.ERR_AmbigMember, "Item2").WithArguments("(T1, T2).Item2", "(T1, T2).Item2").WithLocation(17, 13)
};
// C# 7.0
var comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7));
comp.VerifyEmitDiagnostics(expected);
// C# 7.1
comp = CreateCompilation(
source,
assemblyName: "39f5d0e8-2935-4207-a74d-517a8e55af08",
parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
comp.VerifyEmitDiagnostics(expected);
}
[Fact]
public void TestGetDeconstructionInfoOnIncompleteCode()
{
string source = @"
class C
{
void M() { var (y1, y2) =}
void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; }
}
";
var comp = CreateCompilation(source);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var node = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().First();
Assert.Equal("var (y1, y2) =", node.ToString());
var info = model.GetDeconstructionInfo(node);
Assert.Null(info.Method);
Assert.Empty(info.Nested);
}
[Fact]
public void TestDeconstructStructThis()
{
string source = @"
public struct S
{
int I;
public static void Main()
{
S s = new S();
s.M();
}
public void M()
{
this.I = 42;
var (x, (y, z)) = (this, this /* mutating deconstruction */);
System.Console.Write($""{x.I} {y} {z}"");
}
void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "42 42 43");
}
[Fact]
public void TestDeconstructClassThis()
{
string source = @"
public class C
{
int I;
public static void Main()
{
C c = new C();
c.M();
}
public void M()
{
this.I = 42;
var (x, (y, z)) = (this, this /* mutating deconstruction */);
System.Console.Write($""{x.I} {y} {z}"");
}
void Deconstruct(out int x1, out int x2) { x1 = I++; x2 = I++; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "44 42 43");
}
[Fact]
public void AssigningConditional_OutParams()
{
string source = @"
using System;
class C
{
static void Main()
{
Test(true, false);
Test(false, true);
Test(false, false);
}
static void Test(bool b1, bool b2)
{
M(out int x, out int y, b1, b2);
Console.Write(x);
Console.Write(y);
}
static void M(out int x, out int y, bool b1, bool b2)
{
(x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060");
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.2
IL_0001: brtrue.s IL_0018
IL_0003: ldarg.3
IL_0004: brtrue.s IL_000f
IL_0006: ldarg.0
IL_0007: ldc.i4.s 50
IL_0009: stind.i4
IL_000a: ldarg.1
IL_000b: ldc.i4.s 60
IL_000d: stind.i4
IL_000e: ret
IL_000f: ldarg.0
IL_0010: ldc.i4.s 30
IL_0012: stind.i4
IL_0013: ldarg.1
IL_0014: ldc.i4.s 40
IL_0016: stind.i4
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.s 10
IL_001b: stind.i4
IL_001c: ldarg.1
IL_001d: ldc.i4.s 20
IL_001f: stind.i4
IL_0020: ret
}");
}
[Fact]
public void AssigningConditional_VarDeconstruction()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
}
static void M(bool b1, bool b2)
{
var (x, y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
Console.Write(x);
Console.Write(y);
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060");
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0016
IL_0003: ldarg.1
IL_0004: brtrue.s IL_000e
IL_0006: ldc.i4.s 50
IL_0008: stloc.0
IL_0009: ldc.i4.s 60
IL_000b: stloc.1
IL_000c: br.s IL_001c
IL_000e: ldc.i4.s 30
IL_0010: stloc.0
IL_0011: ldc.i4.s 40
IL_0013: stloc.1
IL_0014: br.s IL_001c
IL_0016: ldc.i4.s 10
IL_0018: stloc.0
IL_0019: ldc.i4.s 20
IL_001b: stloc.1
IL_001c: ldloc.0
IL_001d: call ""void System.Console.Write(int)""
IL_0022: ldloc.1
IL_0023: call ""void System.Console.Write(int)""
IL_0028: ret
}");
}
[Fact]
public void AssigningConditional_MixedDeconstruction()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
}
static void M(bool b1, bool b2)
{
(var x, long y) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
Console.Write(x);
Console.Write(y);
}
}
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "102030405060");
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 50 (0x32)
.maxstack 1
.locals init (int V_0, //x
long V_1, //y
long V_2)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_001c
IL_0003: ldarg.1
IL_0004: brtrue.s IL_0011
IL_0006: ldc.i4.s 60
IL_0008: conv.i8
IL_0009: stloc.2
IL_000a: ldc.i4.s 50
IL_000c: stloc.0
IL_000d: ldloc.2
IL_000e: stloc.1
IL_000f: br.s IL_0025
IL_0011: ldc.i4.s 40
IL_0013: conv.i8
IL_0014: stloc.2
IL_0015: ldc.i4.s 30
IL_0017: stloc.0
IL_0018: ldloc.2
IL_0019: stloc.1
IL_001a: br.s IL_0025
IL_001c: ldc.i4.s 20
IL_001e: conv.i8
IL_001f: stloc.2
IL_0020: ldc.i4.s 10
IL_0022: stloc.0
IL_0023: ldloc.2
IL_0024: stloc.1
IL_0025: ldloc.0
IL_0026: call ""void System.Console.Write(int)""
IL_002b: ldloc.1
IL_002c: call ""void System.Console.Write(long)""
IL_0031: ret
}");
}
[Fact]
public void AssigningConditional_SideEffects()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
SideEffect(true);
SideEffect(false);
}
static int left;
static int right;
static ref int SideEffect(bool isLeft)
{
Console.WriteLine($""{(isLeft ? ""left"" : ""right"")}: {(isLeft ? left : right)}"");
return ref isLeft ? ref left : ref right;
}
static void M(bool b1, bool b2)
{
(SideEffect(isLeft: true), SideEffect(isLeft: false)) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
}
}
";
var expected =
@"left: 0
right: 0
left: 10
right: 20
left: 30
right: 40
left: 50
right: 60";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected);
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (int& V_0,
int& V_1)
IL_0000: ldc.i4.1
IL_0001: call ""ref int C.SideEffect(bool)""
IL_0006: stloc.0
IL_0007: ldc.i4.0
IL_0008: call ""ref int C.SideEffect(bool)""
IL_000d: stloc.1
IL_000e: ldarg.0
IL_000f: brtrue.s IL_0026
IL_0011: ldarg.1
IL_0012: brtrue.s IL_001d
IL_0014: ldloc.0
IL_0015: ldc.i4.s 50
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: ldc.i4.s 60
IL_001b: stind.i4
IL_001c: ret
IL_001d: ldloc.0
IL_001e: ldc.i4.s 30
IL_0020: stind.i4
IL_0021: ldloc.1
IL_0022: ldc.i4.s 40
IL_0024: stind.i4
IL_0025: ret
IL_0026: ldloc.0
IL_0027: ldc.i4.s 10
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: ldc.i4.s 20
IL_002d: stind.i4
IL_002e: ret
}");
}
[Fact]
public void AssigningConditional_SideEffects_RHS()
{
string source = @"
using System;
class C
{
static void Main()
{
M(true, false);
M(false, true);
M(false, false);
}
static T Echo<T>(T v, int i)
{
Console.WriteLine(i + "": "" + v);
return v;
}
static void M(bool b1, bool b2)
{
var (x, y) = Echo(b1, 1) ? Echo((10, 20), 2) : Echo(b2, 3) ? Echo((30, 40), 4) : Echo((50, 60), 5);
Console.WriteLine(""x: "" + x);
Console.WriteLine(""y: "" + y);
Console.WriteLine();
}
}
";
var expectedOutput =
@"1: True
2: (10, 20)
x: 10
y: 20
1: False
3: True
4: (30, 40)
x: 30
y: 40
1: False
3: False
5: (50, 60)
x: 50
y: 60
";
var comp = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
}
[Fact]
public void AssigningConditional_UnusedDeconstruction()
{
string source = @"
class C
{
static void M(bool b1, bool b2)
{
(_, _) = b1 ? (10, 20) : b2 ? (30, 40) : (50, 60);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("C.M", @"
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0005
IL_0003: ldarg.1
IL_0004: pop
IL_0005: ret
}");
}
[Fact, WorkItem(46562, "https://github.com/dotnet/roslyn/issues/46562")]
public void CompoundAssignment()
{
string source = @"
class C
{
void M()
{
decimal x = 0;
(var y, _) += 0.00m;
(int z, _) += z;
(var t, _) += (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (6,17): warning CS0219: The variable 'x' is assigned but its value is never used
// decimal x = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17),
// (7,10): error CS8185: A declaration is not allowed in this context.
// (var y, _) += 0.00m;
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var y").WithLocation(7, 10),
// (7,17): error CS0103: The name '_' does not exist in the current context
// (var y, _) += 0.00m;
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 17),
// (8,10): error CS8185: A declaration is not allowed in this context.
// (int z, _) += z;
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z").WithLocation(8, 10),
// (8,10): error CS0165: Use of unassigned local variable 'z'
// (int z, _) += z;
Diagnostic(ErrorCode.ERR_UseDefViolation, "int z").WithArguments("z").WithLocation(8, 10),
// (8,17): error CS0103: The name '_' does not exist in the current context
// (int z, _) += z;
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 17),
// (9,10): error CS8185: A declaration is not allowed in this context.
// (var t, _) += (1, 2);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var t").WithLocation(9, 10),
// (9,17): error CS0103: The name '_' does not exist in the current context
// (var t, _) += (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 17)
);
}
[Fact, WorkItem(50654, "https://github.com/dotnet/roslyn/issues/50654")]
public void Repro50654()
{
string source = @"
class C
{
static void Main()
{
(int, (int, (int, int), (int, int)))[] vals = new[]
{
(1, (2, (3, 4), (5, 6))),
(11, (12, (13, 14), (15, 16)))
};
foreach (var (a, (b, (c, d), (e, f))) in vals)
{
System.Console.Write($""{a + b + c + d + e + f} "");
}
foreach ((int a, (int b, (int c, int d), (int e, int f))) in vals)
{
System.Console.Write($""{a + b + c + d + e + f} "");
}
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "21 81 21 81");
}
[Fact]
public void MixDeclarationAndAssignmentPermutationsOf2()
{
string source = @"
class C
{
static void Main()
{
int x1 = 0;
(x1, string y1) = new C();
System.Console.WriteLine(x1 + "" "" + y1);
int x2;
(x2, var y2) = new C();
System.Console.WriteLine(x2 + "" "" + y2);
string y3 = """";
(int x3, y3) = new C();
System.Console.WriteLine(x3 + "" "" + y3);
string y4;
(var x4, y4) = new C();
System.Console.WriteLine(x4 + "" "" + y4);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello
1 hello
1 hello
1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 188 (0xbc)
.maxstack 3
.locals init (int V_0, //x1
string V_1, //y1
int V_2, //x2
string V_3, //y2
string V_4, //y3
int V_5, //x3
string V_6, //y4
int V_7, //x4
int V_8,
string V_9)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: newobj ""C..ctor()""
IL_0007: ldloca.s V_8
IL_0009: ldloca.s V_9
IL_000b: callvirt ""void C.Deconstruct(out int, out string)""
IL_0010: ldloc.s V_8
IL_0012: stloc.0
IL_0013: ldloc.s V_9
IL_0015: stloc.1
IL_0016: ldloca.s V_0
IL_0018: call ""string int.ToString()""
IL_001d: ldstr "" ""
IL_0022: ldloc.1
IL_0023: call ""string string.Concat(string, string, string)""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: newobj ""C..ctor()""
IL_0032: ldloca.s V_8
IL_0034: ldloca.s V_9
IL_0036: callvirt ""void C.Deconstruct(out int, out string)""
IL_003b: ldloc.s V_8
IL_003d: stloc.2
IL_003e: ldloc.s V_9
IL_0040: stloc.3
IL_0041: ldloca.s V_2
IL_0043: call ""string int.ToString()""
IL_0048: ldstr "" ""
IL_004d: ldloc.3
IL_004e: call ""string string.Concat(string, string, string)""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ldstr """"
IL_005d: stloc.s V_4
IL_005f: newobj ""C..ctor()""
IL_0064: ldloca.s V_8
IL_0066: ldloca.s V_9
IL_0068: callvirt ""void C.Deconstruct(out int, out string)""
IL_006d: ldloc.s V_8
IL_006f: stloc.s V_5
IL_0071: ldloc.s V_9
IL_0073: stloc.s V_4
IL_0075: ldloca.s V_5
IL_0077: call ""string int.ToString()""
IL_007c: ldstr "" ""
IL_0081: ldloc.s V_4
IL_0083: call ""string string.Concat(string, string, string)""
IL_0088: call ""void System.Console.WriteLine(string)""
IL_008d: newobj ""C..ctor()""
IL_0092: ldloca.s V_8
IL_0094: ldloca.s V_9
IL_0096: callvirt ""void C.Deconstruct(out int, out string)""
IL_009b: ldloc.s V_8
IL_009d: stloc.s V_7
IL_009f: ldloc.s V_9
IL_00a1: stloc.s V_6
IL_00a3: ldloca.s V_7
IL_00a5: call ""string int.ToString()""
IL_00aa: ldstr "" ""
IL_00af: ldloc.s V_6
IL_00b1: call ""string string.Concat(string, string, string)""
IL_00b6: call ""void System.Console.WriteLine(string)""
IL_00bb: ret
}");
}
[Fact]
public void MixDeclarationAndAssignmentPermutationsOf3()
{
string source = @"
class C
{
static void Main()
{
int x1;
string y1;
(x1, y1, var z1) = new C();
System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1);
int x2;
bool z2;
(x2, var y2, z2) = new C();
System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2);
string y3;
bool z3;
(var x3, y3, z3) = new C();
System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3);
bool z4;
(var x4, var y4, z4) = new C();
System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4);
string y5;
(var x5, y5, var z5) = new C();
System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5);
int x6;
(x6, var y6, var z6) = new C();
System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6);
}
public void Deconstruct(out int a, out string b, out bool c)
{
a = 1;
b = ""hello"";
c = true;
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True
1 hello True
1 hello True
1 hello True
1 hello True
1 hello True");
comp.VerifyDiagnostics();
}
[Fact]
public void DontAllowMixedDeclarationAndAssignmentInExpressionContext()
{
string source = @"
class C
{
static void Main()
{
int x1 = 0;
var z1 = (x1, string y1) = new C();
string y2 = """";
var z2 = (int x2, y2) = new C();
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,23): error CS8185: A declaration is not allowed in this context.
// var z1 = (x1, string y1) = new C();
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "string y1").WithLocation(7, 23),
// (9,19): error CS8185: A declaration is not allowed in this context.
// var z2 = (int x2, y2) = new C();
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(9, 19));
}
[Fact]
public void DontAllowMixedDeclarationAndAssignmentInForeachDeclarationVariable()
{
string source = @"
class C
{
static void Main()
{
int x1;
foreach((x1, string y1) in new C[0]);
string y2;
foreach((int x2, y2) in new C[0]);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (6,13): warning CS0168: The variable 'x1' is declared but never used
// int x1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(6, 13),
// (7,17): error CS8186: A foreach loop must declare its iteration variables.
// foreach((x1, string y1) in new C[0]);
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(x1, string y1)").WithLocation(7, 17),
// (8,16): warning CS0168: The variable 'y2' is declared but never used
// string y2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "y2").WithArguments("y2").WithLocation(8, 16),
// (9,17): error CS8186: A foreach loop must declare its iteration variables.
// foreach((int x2, y2) in new C[0]);
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int x2, y2)").WithLocation(9, 17));
}
[Fact]
public void DuplicateDeclarationOfVariableDeclaredInMixedDeclarationAndAssignment()
{
string source = @"
class C
{
static void Main()
{
int x1;
string y1;
(x1, string y1) = new C();
string y2;
(int x2, y2) = new C();
int x2;
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(
// (7,16): warning CS0168: The variable 'y1' is declared but never used
// string y1;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "y1").WithArguments("y1").WithLocation(7, 16),
// (8,21): error CS0128: A local variable or function named 'y1' is already defined in this scope
// (x1, string y1) = new C();
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(8, 21),
// (11,13): error CS0128: A local variable or function named 'x2' is already defined in this scope
// int x2;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(11, 13),
// (11,13): warning CS0168: The variable 'x2' is declared but never used
// int x2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(11, 13));
}
[Fact]
public void AssignmentToUndeclaredVariableInMixedDeclarationAndAssignment()
{
string source = @"
class C
{
static void Main()
{
(x1, string y1) = new C();
(int x2, y2) = new C();
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(
// (6,10): error CS0103: The name 'x1' does not exist in the current context
// (x1, string y1) = new C();
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 10),
// (7,18): error CS0103: The name 'y2' does not exist in the current context
// (int x2, y2) = new C();
Diagnostic(ErrorCode.ERR_NameNotInContext, "y2").WithArguments("y2").WithLocation(7, 18));
}
[Fact]
public void MixedDeclarationAndAssignmentInForInitialization()
{
string source = @"
class C
{
static void Main()
{
int x1;
for((x1, string y1) = new C(); x1 < 2; x1++)
System.Console.WriteLine(x1 + "" "" + y1);
string y2;
for((int x2, y2) = new C(); x2 < 2; x2++)
System.Console.WriteLine(x2 + "" "" + y2);
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello
1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (int V_0, //x1
string V_1, //y2
string V_2, //y1
int V_3,
string V_4,
int V_5) //x2
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_3
IL_0007: ldloca.s V_4
IL_0009: callvirt ""void C.Deconstruct(out int, out string)""
IL_000e: ldloc.3
IL_000f: stloc.0
IL_0010: ldloc.s V_4
IL_0012: stloc.2
IL_0013: br.s IL_0030
IL_0015: ldloca.s V_0
IL_0017: call ""string int.ToString()""
IL_001c: ldstr "" ""
IL_0021: ldloc.2
IL_0022: call ""string string.Concat(string, string, string)""
IL_0027: call ""void System.Console.WriteLine(string)""
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: add
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: ldc.i4.2
IL_0032: blt.s IL_0015
IL_0034: newobj ""C..ctor()""
IL_0039: ldloca.s V_3
IL_003b: ldloca.s V_4
IL_003d: callvirt ""void C.Deconstruct(out int, out string)""
IL_0042: ldloc.3
IL_0043: stloc.s V_5
IL_0045: ldloc.s V_4
IL_0047: stloc.1
IL_0048: br.s IL_0067
IL_004a: ldloca.s V_5
IL_004c: call ""string int.ToString()""
IL_0051: ldstr "" ""
IL_0056: ldloc.1
IL_0057: call ""string string.Concat(string, string, string)""
IL_005c: call ""void System.Console.WriteLine(string)""
IL_0061: ldloc.s V_5
IL_0063: ldc.i4.1
IL_0064: add
IL_0065: stloc.s V_5
IL_0067: ldloc.s V_5
IL_0069: ldc.i4.2
IL_006a: blt.s IL_004a
IL_006c: ret
}");
}
[Fact]
public void MixDeclarationAndAssignmentInTupleDeconstructPermutationsOf2()
{
string source = @"
class C
{
static void Main()
{
int x1 = 0;
(x1, string y1) = (1, ""hello"");
System.Console.WriteLine(x1 + "" "" + y1);
int x2;
(x2, var y2) = (1, ""hello"");
System.Console.WriteLine(x2 + "" "" + y2);
string y3 = """";
(int x3, y3) = (1, ""hello"");
System.Console.WriteLine(x3 + "" "" + y3);
string y4;
(var x4, y4) = (1, ""hello"");
System.Console.WriteLine(x4 + "" "" + y4);
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello
1 hello
1 hello
1 hello");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"
{
// Code size 140 (0x8c)
.maxstack 3
.locals init (int V_0, //x1
string V_1, //y1
int V_2, //x2
string V_3, //y2
string V_4, //y3
int V_5, //x3
string V_6, //y4
int V_7) //x4
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: stloc.0
IL_0004: ldstr ""hello""
IL_0009: stloc.1
IL_000a: ldloca.s V_0
IL_000c: call ""string int.ToString()""
IL_0011: ldstr "" ""
IL_0016: ldloc.1
IL_0017: call ""string string.Concat(string, string, string)""
IL_001c: call ""void System.Console.WriteLine(string)""
IL_0021: ldc.i4.1
IL_0022: stloc.2
IL_0023: ldstr ""hello""
IL_0028: stloc.3
IL_0029: ldloca.s V_2
IL_002b: call ""string int.ToString()""
IL_0030: ldstr "" ""
IL_0035: ldloc.3
IL_0036: call ""string string.Concat(string, string, string)""
IL_003b: call ""void System.Console.WriteLine(string)""
IL_0040: ldstr """"
IL_0045: stloc.s V_4
IL_0047: ldc.i4.1
IL_0048: stloc.s V_5
IL_004a: ldstr ""hello""
IL_004f: stloc.s V_4
IL_0051: ldloca.s V_5
IL_0053: call ""string int.ToString()""
IL_0058: ldstr "" ""
IL_005d: ldloc.s V_4
IL_005f: call ""string string.Concat(string, string, string)""
IL_0064: call ""void System.Console.WriteLine(string)""
IL_0069: ldc.i4.1
IL_006a: stloc.s V_7
IL_006c: ldstr ""hello""
IL_0071: stloc.s V_6
IL_0073: ldloca.s V_7
IL_0075: call ""string int.ToString()""
IL_007a: ldstr "" ""
IL_007f: ldloc.s V_6
IL_0081: call ""string string.Concat(string, string, string)""
IL_0086: call ""void System.Console.WriteLine(string)""
IL_008b: ret
}");
}
[Fact]
public void MixedDeclarationAndAssignmentCSharpNine()
{
string source = @"
class Program
{
static void Main()
{
int x1;
(x1, string y1) = new A();
string y2;
(int x2, y2) = new A();
bool z3;
(int x3, (string y3, z3)) = new B();
int x4;
(x4, var (y4, z4)) = new B();
}
}
class A
{
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
class B
{
public void Deconstruct(out int a, out (string b, bool c) tuple)
{
a = 1;
tuple = (""hello"", true);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics(
// (7,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (x1, string y1) = new A();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x1, string y1) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(7, 9),
// (9,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (int x2, y2) = new A();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x2, y2) = new A()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(9, 9),
// (11,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (int x3, (string y3, z3)) = new B();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(int x3, (string y3, z3)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(11, 9),
// (13,9): error CS8773: Feature 'Mixed declarations and expressions in deconstruction' is not available in C# 9.0. Please use language version 10.0 or greater.
// (x4, var (y4, z4)) = new B();
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(x4, var (y4, z4)) = new B()").WithArguments("Mixed declarations and expressions in deconstruction", "10.0").WithLocation(13, 9));
}
[Fact]
public void NestedMixedDeclarationAndAssignmentPermutations()
{
string source = @"
class C
{
static void Main()
{
int x1;
string y1;
(x1, (y1, var z1)) = new C();
System.Console.WriteLine(x1 + "" "" + y1 + "" "" + z1);
int x2;
bool z2;
(x2, (var y2, z2)) = new C();
System.Console.WriteLine(x2 + "" "" + y2 + "" "" + z2);
string y3;
bool z3;
(var x3, (y3, z3)) = new C();
System.Console.WriteLine(x3 + "" "" + y3 + "" "" + z3);
bool z4;
(var x4, (var y4, z4)) = new C();
System.Console.WriteLine(x4 + "" "" + y4 + "" "" + z4);
string y5;
(var x5, (y5, var z5)) = new C();
System.Console.WriteLine(x5 + "" "" + y5 + "" "" + z5);
int x6;
(x6, (var y6, var z6)) = new C();
System.Console.WriteLine(x6 + "" "" + y6 + "" "" + z6);
int x7;
(x7, var (y7, z7)) = new C();
System.Console.WriteLine(x7 + "" "" + y7 + "" "" + z7);
}
public void Deconstruct(out int a, out (string a, bool b) b)
{
a = 1;
b = (""hello"", true);
}
}
";
var comp = CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"1 hello True
1 hello True
1 hello True
1 hello True
1 hello True
1 hello True
1 hello True");
comp.VerifyDiagnostics();
}
[Fact]
public void MixedDeclarationAndAssignmentUseBeforeDeclaration()
{
string source = @"
class Program
{
static void Main()
{
(x1, string y1) = new A();
int x1;
(int x2, y2) = new A();
string y2;
(int x3, (string y3, z3)) = new B();
bool z3;
(x4, var (y4, z4)) = new B();
int x4;
}
}
class A
{
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
class B
{
public void Deconstruct(out int a, out (string b, bool c) tuple)
{
a = 1;
tuple = (""hello"", true);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview)
.VerifyDiagnostics(
// (6,10): error CS0841: Cannot use local variable 'x1' before it is declared
// (x1, string y1) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1", isSuppressed: false).WithArguments("x1").WithLocation(6, 10),
// (8,18): error CS0841: Cannot use local variable 'y2' before it is declared
// (int x2, y2) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y2", isSuppressed: false).WithArguments("y2").WithLocation(8, 18),
// (10,30): error CS0841: Cannot use local variable 'z3' before it is declared
// (int x3, (string y3, z3)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "z3", isSuppressed: false).WithArguments("z3").WithLocation(10, 30),
// (12,10): error CS0841: Cannot use local variable 'x4' before it is declared
// (x4, var (y4, z4)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4", isSuppressed: false).WithArguments("x4").WithLocation(12, 10));
}
[Fact]
public void MixedDeclarationAndAssignmentUseDeclaredVariableInAssignment()
{
string source = @"
class Program
{
static void Main()
{
(var x1, x1) = new A();
(x2, var x2) = new A();
(var x3, (var y3, x3)) = new B();
(x4, (var y4, var x4)) = new B();
}
}
class A
{
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
class B
{
public void Deconstruct(out int a, out (string b, bool c) tuple)
{
a = 1;
tuple = (""hello"", true);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.RegularPreview)
.VerifyDiagnostics(
// (6,18): error CS0841: Cannot use local variable 'x1' before it is declared
// (var x1, x1) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 18),
// (7,10): error CS0841: Cannot use local variable 'x2' before it is declared
// (x2, var x2) = new A();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(7, 10),
// (8,27): error CS0841: Cannot use local variable 'x3' before it is declared
// (var x3, (var y3, x3)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x3").WithArguments("x3").WithLocation(8, 27),
// (9,10): error CS0841: Cannot use local variable 'x4' before it is declared
// (x4, (var y4, var x4)) = new B();
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 10));
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/ParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class ParameterSymbol : Symbol, IParameterSymbol
{
private readonly Symbols.ParameterSymbol _underlying;
private ITypeSymbol _lazyType;
public ParameterSymbol(Symbols.ParameterSymbol underlying)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
ITypeSymbol IParameterSymbol.Type
{
get
{
if (_lazyType is null)
{
Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyType;
}
}
CodeAnalysis.NullableAnnotation IParameterSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation();
ImmutableArray<CustomModifier> IParameterSymbol.CustomModifiers
{
get { return _underlying.TypeWithAnnotations.CustomModifiers; }
}
ImmutableArray<CustomModifier> IParameterSymbol.RefCustomModifiers
{
get { return _underlying.RefCustomModifiers; }
}
IParameterSymbol IParameterSymbol.OriginalDefinition
{
get
{
return _underlying.OriginalDefinition.GetPublicSymbol();
}
}
RefKind IParameterSymbol.RefKind => _underlying.RefKind;
bool IParameterSymbol.IsDiscard => _underlying.IsDiscard;
bool IParameterSymbol.IsParams => _underlying.IsParams;
bool IParameterSymbol.IsOptional => _underlying.IsOptional;
bool IParameterSymbol.IsThis => _underlying.IsThis;
int IParameterSymbol.Ordinal => _underlying.Ordinal;
bool IParameterSymbol.HasExplicitDefaultValue => _underlying.HasExplicitDefaultValue;
object IParameterSymbol.ExplicitDefaultValue => _underlying.ExplicitDefaultValue;
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitParameter(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitParameter(this);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class ParameterSymbol : Symbol, IParameterSymbol
{
private readonly Symbols.ParameterSymbol _underlying;
private ITypeSymbol _lazyType;
public ParameterSymbol(Symbols.ParameterSymbol underlying)
{
Debug.Assert(underlying is object);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
ITypeSymbol IParameterSymbol.Type
{
get
{
if (_lazyType is null)
{
Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyType;
}
}
CodeAnalysis.NullableAnnotation IParameterSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation();
ImmutableArray<CustomModifier> IParameterSymbol.CustomModifiers
{
get { return _underlying.TypeWithAnnotations.CustomModifiers; }
}
ImmutableArray<CustomModifier> IParameterSymbol.RefCustomModifiers
{
get { return _underlying.RefCustomModifiers; }
}
IParameterSymbol IParameterSymbol.OriginalDefinition
{
get
{
return _underlying.OriginalDefinition.GetPublicSymbol();
}
}
RefKind IParameterSymbol.RefKind => _underlying.RefKind;
bool IParameterSymbol.IsDiscard => _underlying.IsDiscard;
bool IParameterSymbol.IsParams => _underlying.IsParams;
bool IParameterSymbol.IsOptional => _underlying.IsOptional;
bool IParameterSymbol.IsThis => _underlying.IsThis;
int IParameterSymbol.Ordinal => _underlying.Ordinal;
bool IParameterSymbol.HasExplicitDefaultValue => _underlying.HasExplicitDefaultValue;
object IParameterSymbol.ExplicitDefaultValue => _underlying.ExplicitDefaultValue;
#region ISymbol Members
protected override void Accept(SymbolVisitor visitor)
{
visitor.VisitParameter(this);
}
protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitParameter(this);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_Hierarchy.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Find symbols for members that override the specified member symbol.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindOverridesAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
return await FindOverridesArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindOverridesAsync"/>
/// <remarks>
/// Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.
/// </remarks>
internal static async Task<ImmutableArray<ISymbol>> FindOverridesArrayAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var results = ArrayBuilder<ISymbol>.GetInstance();
symbol = symbol?.OriginalDefinition;
if (symbol.IsOverridable())
{
// To find the overrides, we need to walk down the type hierarchy and check all
// derived types.
var containingType = symbol.ContainingType;
var derivedTypes = await FindDerivedClassesAsync(
containingType, solution, projects, cancellationToken).ConfigureAwait(false);
foreach (var type in derivedTypes)
{
foreach (var m in type.GetMembers(symbol.Name))
{
var sourceMember = await FindSourceDefinitionAsync(m, solution, cancellationToken).ConfigureAwait(false);
var bestMember = sourceMember ?? m;
if (await IsOverrideAsync(solution, bestMember, symbol, cancellationToken).ConfigureAwait(false))
{
results.Add(bestMember);
}
}
}
}
return results.ToImmutableAndFree();
}
internal static async Task<bool> IsOverrideAsync(Solution solution, ISymbol member, ISymbol symbol, CancellationToken cancellationToken)
{
for (var current = member; current != null; current = current.GetOverriddenMember())
{
if (await OriginalSymbolsMatchAsync(solution, current.GetOverriddenMember(), symbol.OriginalDefinition, cancellationToken).ConfigureAwait(false))
return true;
}
return false;
}
/// <summary>
/// Find symbols for declarations that implement members of the specified interface symbol
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindImplementedInterfaceMembersAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
return await FindImplementedInterfaceMembersArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindImplementedInterfaceMembersAsync"/>
/// <remarks>
/// Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.
/// </remarks>
internal static async Task<ImmutableArray<ISymbol>> FindImplementedInterfaceMembersArrayAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
// Member can only implement interface members if it is an explicit member, or if it is
// public
if (symbol != null)
{
var explicitImplementations = symbol.ExplicitInterfaceImplementations();
if (explicitImplementations.Length > 0)
{
return explicitImplementations;
}
else if (
symbol.DeclaredAccessibility == Accessibility.Public &&
(symbol.ContainingType.TypeKind == TypeKind.Class || symbol.ContainingType.TypeKind == TypeKind.Struct))
{
// Interface implementation is a tricky thing. A method may implement an interface
// method, even if its containing type doesn't state that it implements the
// interface. For example:
//
// interface IGoo { void Goo(); }
//
// class Base { public void Goo(); }
//
// class Derived : Base, IGoo { }
//
// In this case, Base.Goo *does* implement IGoo.Goo in the context of the type
// Derived.
var containingType = symbol.ContainingType.OriginalDefinition;
var derivedClasses = await SymbolFinder.FindDerivedClassesAsync(
containingType, solution, projects, cancellationToken).ConfigureAwait(false);
var allTypes = derivedClasses.Concat(containingType);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder);
foreach (var type in allTypes)
{
foreach (var interfaceType in type.AllInterfaces)
{
// We don't want to look inside this type if we can avoid it. So first
// make sure that the interface even contains a symbol with the same
// name as the symbol we're looking for.
var nameToLookFor = symbol.IsPropertyAccessor()
? ((IMethodSymbol)symbol).AssociatedSymbol.Name
: symbol.Name;
if (interfaceType.MemberNames.Contains(nameToLookFor))
{
foreach (var m in interfaceType.GetMembers(symbol.Name))
{
var sourceMethod = await FindSourceDefinitionAsync(m, solution, cancellationToken).ConfigureAwait(false);
var bestMethod = sourceMethod ?? m;
var implementations = await type.FindImplementationsForInterfaceMemberAsync(bestMethod, solution, cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
if (implementation != null &&
SymbolEquivalenceComparer.Instance.Equals(implementation.OriginalDefinition, symbol.OriginalDefinition))
{
builder.Add(bestMethod);
}
}
}
}
}
}
return builder.Distinct(SymbolEquivalenceComparer.Instance).ToImmutableArray();
}
}
return ImmutableArray<ISymbol>.Empty;
}
#region derived classes
/// <summary>
/// Finds all the derived classes of the given type. Implementations of an interface are not considered
/// "derived", but can be found with <see cref="FindImplementationsAsync(ISymbol, Solution,
/// IImmutableSet{Project}, CancellationToken)"/>.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
/// <param name="cancellationToken"></param>
/// <returns>The derived types of the symbol. The symbol passed in is not included in this list.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static Task<IEnumerable<INamedTypeSymbol>> FindDerivedClassesAsync(
INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken)
{
return FindDerivedClassesAsync(type, solution, transitive: true, projects, cancellationToken);
}
/// <summary>
/// Finds the derived classes of the given type. Implementations of an interface are not considered
/// "derived", but can be found with <see cref="FindImplementationsAsync(ISymbol, Solution,
/// IImmutableSet{Project}, CancellationToken)"/>.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="transitive">If the search should stop at immediately derived classes, or should continue past that.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
/// <param name="cancellationToken"></param>
/// <returns>The derived types of the symbol. The symbol passed in is not included in this list.</returns>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public static async Task<IEnumerable<INamedTypeSymbol>> FindDerivedClassesAsync(
INamedTypeSymbol type, Solution solution, bool transitive = true, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
return await FindDerivedClassesArrayAsync(type, solution, transitive, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindDerivedClassesArrayAsync(INamedTypeSymbol, Solution, bool, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks> Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.</remarks>
internal static async Task<ImmutableArray<INamedTypeSymbol>> FindDerivedClassesArrayAsync(
INamedTypeSymbol type, Solution solution, bool transitive, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var types = await DependentTypeFinder.FindTypesAsync(
type, solution, projects, transitive, DependentTypesKind.DerivedClasses, cancellationToken).ConfigureAwait(false);
return types.WhereAsArray(t => IsAccessible(t));
}
#endregion
#region derived interfaces
/// <summary>
/// Finds the derived interfaces of the given interfaces.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="transitive">If the search should stop at immediately derived interfaces, or should continue past that.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
/// <returns>The derived interfaces of the symbol. The symbol passed in is not included in this list.</returns>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public static async Task<IEnumerable<INamedTypeSymbol>> FindDerivedInterfacesAsync(
INamedTypeSymbol type, Solution solution, bool transitive = true, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
return await FindDerivedInterfacesArrayAsync(type, solution, transitive, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindDerivedInterfacesAsync(INamedTypeSymbol, Solution, bool, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks> Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.</remarks>
internal static async Task<ImmutableArray<INamedTypeSymbol>> FindDerivedInterfacesArrayAsync(
INamedTypeSymbol type, Solution solution, bool transitive, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var types = await DependentTypeFinder.FindTypesAsync(
type, solution, projects, transitive, DependentTypesKind.DerivedInterfaces, cancellationToken).ConfigureAwait(false);
return types.WhereAsArray(t => IsAccessible(t));
}
#endregion
#region interface implementations
/// <summary>
/// Finds the accessible <see langword="class"/> or <see langword="struct"/> types that implement the given
/// interface.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="transitive">If the search should stop at immediately derived interfaces, or should continue past that.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public static async Task<IEnumerable<INamedTypeSymbol>> FindImplementationsAsync(
INamedTypeSymbol type, Solution solution, bool transitive = true, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
return await FindImplementationsArrayAsync(type, solution, transitive, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindImplementationsAsync(INamedTypeSymbol, Solution, bool, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks> Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.</remarks>
internal static async Task<ImmutableArray<INamedTypeSymbol>> FindImplementationsArrayAsync(
INamedTypeSymbol type, Solution solution, bool transitive, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var types = await DependentTypeFinder.FindTypesAsync(
type, solution, projects, transitive, DependentTypesKind.ImplementingTypes, cancellationToken).ConfigureAwait(false);
return types.WhereAsArray(t => IsAccessible(t));
}
#endregion
/// <summary>
/// Finds all the accessible symbols that implement an interface or interface member. For an <see
/// cref="INamedTypeSymbol"/> this will be both immediate and transitive implementations.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindImplementationsAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
if (symbol == null)
throw new ArgumentNullException(nameof(symbol));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
// A symbol can only have implementations if it's an interface or a
// method/property/event from an interface.
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
return await FindImplementationsAsync(
namedTypeSymbol, solution, transitive: true, projects, cancellationToken).ConfigureAwait(false);
}
return await FindMemberImplementationsArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindImplementationsAsync(ISymbol, Solution, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks>
/// Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.
/// </remarks>
internal static async Task<ImmutableArray<ISymbol>> FindMemberImplementationsArrayAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
if (!symbol.IsImplementableMember())
return ImmutableArray<ISymbol>.Empty;
var containingType = symbol.ContainingType.OriginalDefinition;
// implementations could be found in any class/struct implementations of the containing interface. And, in
// the case of DIM, they could be found in any derived interface.
var classAndStructImplementations = await FindImplementationsAsync(containingType, solution, transitive: true, projects, cancellationToken).ConfigureAwait(false);
var transitiveDerivedInterfaces = await FindDerivedInterfacesAsync(containingType, solution, transitive: true, projects, cancellationToken).ConfigureAwait(false);
var allTypes = classAndStructImplementations.Concat(transitiveDerivedInterfaces);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var results);
foreach (var t in allTypes)
{
var implementations = await t.FindImplementationsForInterfaceMemberAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
var sourceDef = await FindSourceDefinitionAsync(implementation, solution, cancellationToken).ConfigureAwait(false);
var bestDef = sourceDef ?? implementation;
if (IsAccessible(bestDef))
results.Add(bestDef.OriginalDefinition);
}
}
return results.Distinct(SymbolEquivalenceComparer.Instance).ToImmutableArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
public static partial class SymbolFinder
{
/// <summary>
/// Find symbols for members that override the specified member symbol.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindOverridesAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
return await FindOverridesArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindOverridesAsync"/>
/// <remarks>
/// Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.
/// </remarks>
internal static async Task<ImmutableArray<ISymbol>> FindOverridesArrayAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var results = ArrayBuilder<ISymbol>.GetInstance();
symbol = symbol?.OriginalDefinition;
if (symbol.IsOverridable())
{
// To find the overrides, we need to walk down the type hierarchy and check all
// derived types.
var containingType = symbol.ContainingType;
var derivedTypes = await FindDerivedClassesAsync(
containingType, solution, projects, cancellationToken).ConfigureAwait(false);
foreach (var type in derivedTypes)
{
foreach (var m in type.GetMembers(symbol.Name))
{
var sourceMember = await FindSourceDefinitionAsync(m, solution, cancellationToken).ConfigureAwait(false);
var bestMember = sourceMember ?? m;
if (await IsOverrideAsync(solution, bestMember, symbol, cancellationToken).ConfigureAwait(false))
{
results.Add(bestMember);
}
}
}
}
return results.ToImmutableAndFree();
}
internal static async Task<bool> IsOverrideAsync(Solution solution, ISymbol member, ISymbol symbol, CancellationToken cancellationToken)
{
for (var current = member; current != null; current = current.GetOverriddenMember())
{
if (await OriginalSymbolsMatchAsync(solution, current.GetOverriddenMember(), symbol.OriginalDefinition, cancellationToken).ConfigureAwait(false))
return true;
}
return false;
}
/// <summary>
/// Find symbols for declarations that implement members of the specified interface symbol
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindImplementedInterfaceMembersAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
return await FindImplementedInterfaceMembersArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindImplementedInterfaceMembersAsync"/>
/// <remarks>
/// Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.
/// </remarks>
internal static async Task<ImmutableArray<ISymbol>> FindImplementedInterfaceMembersArrayAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
// Member can only implement interface members if it is an explicit member, or if it is
// public
if (symbol != null)
{
var explicitImplementations = symbol.ExplicitInterfaceImplementations();
if (explicitImplementations.Length > 0)
{
return explicitImplementations;
}
else if (
symbol.DeclaredAccessibility == Accessibility.Public &&
(symbol.ContainingType.TypeKind == TypeKind.Class || symbol.ContainingType.TypeKind == TypeKind.Struct))
{
// Interface implementation is a tricky thing. A method may implement an interface
// method, even if its containing type doesn't state that it implements the
// interface. For example:
//
// interface IGoo { void Goo(); }
//
// class Base { public void Goo(); }
//
// class Derived : Base, IGoo { }
//
// In this case, Base.Goo *does* implement IGoo.Goo in the context of the type
// Derived.
var containingType = symbol.ContainingType.OriginalDefinition;
var derivedClasses = await SymbolFinder.FindDerivedClassesAsync(
containingType, solution, projects, cancellationToken).ConfigureAwait(false);
var allTypes = derivedClasses.Concat(containingType);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder);
foreach (var type in allTypes)
{
foreach (var interfaceType in type.AllInterfaces)
{
// We don't want to look inside this type if we can avoid it. So first
// make sure that the interface even contains a symbol with the same
// name as the symbol we're looking for.
var nameToLookFor = symbol.IsPropertyAccessor()
? ((IMethodSymbol)symbol).AssociatedSymbol.Name
: symbol.Name;
if (interfaceType.MemberNames.Contains(nameToLookFor))
{
foreach (var m in interfaceType.GetMembers(symbol.Name))
{
var sourceMethod = await FindSourceDefinitionAsync(m, solution, cancellationToken).ConfigureAwait(false);
var bestMethod = sourceMethod ?? m;
var implementations = await type.FindImplementationsForInterfaceMemberAsync(bestMethod, solution, cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
if (implementation != null &&
SymbolEquivalenceComparer.Instance.Equals(implementation.OriginalDefinition, symbol.OriginalDefinition))
{
builder.Add(bestMethod);
}
}
}
}
}
}
return builder.Distinct(SymbolEquivalenceComparer.Instance).ToImmutableArray();
}
}
return ImmutableArray<ISymbol>.Empty;
}
#region derived classes
/// <summary>
/// Finds all the derived classes of the given type. Implementations of an interface are not considered
/// "derived", but can be found with <see cref="FindImplementationsAsync(ISymbol, Solution,
/// IImmutableSet{Project}, CancellationToken)"/>.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
/// <param name="cancellationToken"></param>
/// <returns>The derived types of the symbol. The symbol passed in is not included in this list.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static Task<IEnumerable<INamedTypeSymbol>> FindDerivedClassesAsync(
INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken)
{
return FindDerivedClassesAsync(type, solution, transitive: true, projects, cancellationToken);
}
/// <summary>
/// Finds the derived classes of the given type. Implementations of an interface are not considered
/// "derived", but can be found with <see cref="FindImplementationsAsync(ISymbol, Solution,
/// IImmutableSet{Project}, CancellationToken)"/>.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="transitive">If the search should stop at immediately derived classes, or should continue past that.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
/// <param name="cancellationToken"></param>
/// <returns>The derived types of the symbol. The symbol passed in is not included in this list.</returns>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public static async Task<IEnumerable<INamedTypeSymbol>> FindDerivedClassesAsync(
INamedTypeSymbol type, Solution solution, bool transitive = true, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
return await FindDerivedClassesArrayAsync(type, solution, transitive, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindDerivedClassesArrayAsync(INamedTypeSymbol, Solution, bool, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks> Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.</remarks>
internal static async Task<ImmutableArray<INamedTypeSymbol>> FindDerivedClassesArrayAsync(
INamedTypeSymbol type, Solution solution, bool transitive, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var types = await DependentTypeFinder.FindTypesAsync(
type, solution, projects, transitive, DependentTypesKind.DerivedClasses, cancellationToken).ConfigureAwait(false);
return types.WhereAsArray(t => IsAccessible(t));
}
#endregion
#region derived interfaces
/// <summary>
/// Finds the derived interfaces of the given interfaces.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="transitive">If the search should stop at immediately derived interfaces, or should continue past that.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
/// <returns>The derived interfaces of the symbol. The symbol passed in is not included in this list.</returns>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public static async Task<IEnumerable<INamedTypeSymbol>> FindDerivedInterfacesAsync(
INamedTypeSymbol type, Solution solution, bool transitive = true, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
return await FindDerivedInterfacesArrayAsync(type, solution, transitive, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindDerivedInterfacesAsync(INamedTypeSymbol, Solution, bool, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks> Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.</remarks>
internal static async Task<ImmutableArray<INamedTypeSymbol>> FindDerivedInterfacesArrayAsync(
INamedTypeSymbol type, Solution solution, bool transitive, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var types = await DependentTypeFinder.FindTypesAsync(
type, solution, projects, transitive, DependentTypesKind.DerivedInterfaces, cancellationToken).ConfigureAwait(false);
return types.WhereAsArray(t => IsAccessible(t));
}
#endregion
#region interface implementations
/// <summary>
/// Finds the accessible <see langword="class"/> or <see langword="struct"/> types that implement the given
/// interface.
/// </summary>
/// <param name="type">The symbol to find derived types of.</param>
/// <param name="solution">The solution to search in.</param>
/// <param name="transitive">If the search should stop at immediately derived interfaces, or should continue past that.</param>
/// <param name="projects">The projects to search. Can be null to search the entire solution.</param>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
public static async Task<IEnumerable<INamedTypeSymbol>> FindImplementationsAsync(
INamedTypeSymbol type, Solution solution, bool transitive = true, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
return await FindImplementationsArrayAsync(type, solution, transitive, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindImplementationsAsync(INamedTypeSymbol, Solution, bool, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks> Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.</remarks>
internal static async Task<ImmutableArray<INamedTypeSymbol>> FindImplementationsArrayAsync(
INamedTypeSymbol type, Solution solution, bool transitive, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
var types = await DependentTypeFinder.FindTypesAsync(
type, solution, projects, transitive, DependentTypesKind.ImplementingTypes, cancellationToken).ConfigureAwait(false);
return types.WhereAsArray(t => IsAccessible(t));
}
#endregion
/// <summary>
/// Finds all the accessible symbols that implement an interface or interface member. For an <see
/// cref="INamedTypeSymbol"/> this will be both immediate and transitive implementations.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindImplementationsAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
if (symbol == null)
throw new ArgumentNullException(nameof(symbol));
if (solution == null)
throw new ArgumentNullException(nameof(solution));
// A symbol can only have implementations if it's an interface or a
// method/property/event from an interface.
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
return await FindImplementationsAsync(
namedTypeSymbol, solution, transitive: true, projects, cancellationToken).ConfigureAwait(false);
}
return await FindMemberImplementationsArrayAsync(symbol, solution, projects, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc cref="FindImplementationsAsync(ISymbol, Solution, IImmutableSet{Project}, CancellationToken)"/>
/// <remarks>
/// Use this overload to avoid boxing the result into an <see cref="IEnumerable{T}"/>.
/// </remarks>
internal static async Task<ImmutableArray<ISymbol>> FindMemberImplementationsArrayAsync(
ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default)
{
if (!symbol.IsImplementableMember())
return ImmutableArray<ISymbol>.Empty;
var containingType = symbol.ContainingType.OriginalDefinition;
// implementations could be found in any class/struct implementations of the containing interface. And, in
// the case of DIM, they could be found in any derived interface.
var classAndStructImplementations = await FindImplementationsAsync(containingType, solution, transitive: true, projects, cancellationToken).ConfigureAwait(false);
var transitiveDerivedInterfaces = await FindDerivedInterfacesAsync(containingType, solution, transitive: true, projects, cancellationToken).ConfigureAwait(false);
var allTypes = classAndStructImplementations.Concat(transitiveDerivedInterfaces);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var results);
foreach (var t in allTypes)
{
var implementations = await t.FindImplementationsForInterfaceMemberAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
foreach (var implementation in implementations)
{
var sourceDef = await FindSourceDefinitionAsync(implementation, solution, cancellationToken).ConfigureAwait(false);
var bestDef = sourceDef ?? implementation;
if (IsAccessible(bestDef))
results.Add(bestDef.OriginalDefinition);
}
}
return results.Distinct(SymbolEquivalenceComparer.Instance).ToImmutableArray();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Symbol/Symbols/MockNamedTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class MockNamedTypeSymbol : NamedTypeSymbol, IMockSymbol
{
private Symbol _container;
private readonly string _name;
private readonly TypeKind _typeKind;
private readonly IEnumerable<Symbol> _children;
public void SetContainer(Symbol container)
{
_container = container;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
=> throw new NotImplementedException();
public override int Arity
{
get
{
return 0;
}
}
internal override bool MangleName
{
get
{
return Arity > 0;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
return ImmutableArray.Create<TypeParameterSymbol>();
}
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
return ImmutableArray.Create<TypeWithAnnotations>();
}
}
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
public override string Name
{
get
{
return _name;
}
}
internal override bool HasSpecialName
{
get { throw new NotImplementedException(); }
}
public override IEnumerable<string> MemberNames
{
get
{
throw new NotImplementedException();
}
}
public override ImmutableArray<Symbol> GetMembers()
{
return _children.AsImmutable();
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
throw new NotImplementedException();
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return (from sym in _children
where sym.Name == name
select sym).ToArray().AsImmutableOrNull();
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.GetMembers();
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.GetMembers(name);
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return (from sym in _children
where sym is NamedTypeSymbol
select (NamedTypeSymbol)sym).ToArray().AsImmutableOrNull();
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return (from sym in _children
where sym is NamedTypeSymbol && sym.Name == name && ((NamedTypeSymbol)sym).Arity == arity
select (NamedTypeSymbol)sym).ToArray().AsImmutableOrNull();
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return (from sym in _children
where sym is NamedTypeSymbol && sym.Name == name
select (NamedTypeSymbol)sym).ToArray().AsImmutableOrNull();
}
public override TypeKind TypeKind
{
get { return _typeKind; }
}
internal override bool IsInterface
{
get { return _typeKind == TypeKind.Interface; }
}
public override Symbol ContainingSymbol
{
get { return null; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray.Create<Location>(); }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray.Create<SyntaxReference>();
}
}
public MockNamedTypeSymbol(string name, IEnumerable<Symbol> children, TypeKind kind = TypeKind.Class)
{
_name = name;
_children = children;
_typeKind = kind;
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.Public;
}
}
public override bool IsStatic
{
get
{
return false;
}
}
public sealed override bool IsRefLikeType
{
get
{
return false;
}
}
public sealed override bool IsReadOnly
{
get
{
return false;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public sealed override bool AreLocalsZeroed
{
get
{
throw ExceptionUtilities.Unreachable;
}
}
public override bool MightContainExtensionMethods
{
get
{
throw new NotImplementedException();
}
}
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => throw new NotImplementedException();
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
throw new NotImplementedException();
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
throw new NotImplementedException();
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
throw new NotImplementedException();
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
throw new NotImplementedException();
}
internal override bool HasCodeAnalysisEmbeddedAttribute => false;
internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Managed;
internal override bool ShouldAddWinRTMembers
{
get { return false; }
}
internal override bool IsWindowsRuntimeImport
{
get
{
return false;
}
}
internal override bool IsComImport
{
get { return false; }
}
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
internal override TypeLayout Layout
{
get { return default(TypeLayout); }
}
internal override System.Runtime.InteropServices.CharSet MarshallingCharSet
{
get { return DefaultMarshallingCharSet; }
}
public override bool IsSerializable
{
get { return false; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
return null;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override AttributeUsageInfo GetAttributeUsageInfo()
{
return AttributeUsageInfo.Null;
}
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
internal override bool IsRecord => false;
internal override bool IsRecordStruct => false;
internal override bool HasPossibleWellKnownCloneMethod() => false;
internal override bool IsInterpolatedStringHandlerType => false;
internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class MockNamedTypeSymbol : NamedTypeSymbol, IMockSymbol
{
private Symbol _container;
private readonly string _name;
private readonly TypeKind _typeKind;
private readonly IEnumerable<Symbol> _children;
public void SetContainer(Symbol container)
{
_container = container;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
=> throw new NotImplementedException();
public override int Arity
{
get
{
return 0;
}
}
internal override bool MangleName
{
get
{
return Arity > 0;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
return ImmutableArray.Create<TypeParameterSymbol>();
}
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
return ImmutableArray.Create<TypeWithAnnotations>();
}
}
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
public override string Name
{
get
{
return _name;
}
}
internal override bool HasSpecialName
{
get { throw new NotImplementedException(); }
}
public override IEnumerable<string> MemberNames
{
get
{
throw new NotImplementedException();
}
}
public override ImmutableArray<Symbol> GetMembers()
{
return _children.AsImmutable();
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
throw new NotImplementedException();
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return (from sym in _children
where sym.Name == name
select sym).ToArray().AsImmutableOrNull();
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.GetMembers();
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.GetMembers(name);
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return (from sym in _children
where sym is NamedTypeSymbol
select (NamedTypeSymbol)sym).ToArray().AsImmutableOrNull();
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return (from sym in _children
where sym is NamedTypeSymbol && sym.Name == name && ((NamedTypeSymbol)sym).Arity == arity
select (NamedTypeSymbol)sym).ToArray().AsImmutableOrNull();
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return (from sym in _children
where sym is NamedTypeSymbol && sym.Name == name
select (NamedTypeSymbol)sym).ToArray().AsImmutableOrNull();
}
public override TypeKind TypeKind
{
get { return _typeKind; }
}
internal override bool IsInterface
{
get { return _typeKind == TypeKind.Interface; }
}
public override Symbol ContainingSymbol
{
get { return null; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray.Create<Location>(); }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray.Create<SyntaxReference>();
}
}
public MockNamedTypeSymbol(string name, IEnumerable<Symbol> children, TypeKind kind = TypeKind.Class)
{
_name = name;
_children = children;
_typeKind = kind;
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.Public;
}
}
public override bool IsStatic
{
get
{
return false;
}
}
public sealed override bool IsRefLikeType
{
get
{
return false;
}
}
public sealed override bool IsReadOnly
{
get
{
return false;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public sealed override bool AreLocalsZeroed
{
get
{
throw ExceptionUtilities.Unreachable;
}
}
public override bool MightContainExtensionMethods
{
get
{
throw new NotImplementedException();
}
}
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => throw new NotImplementedException();
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
throw new NotImplementedException();
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
throw new NotImplementedException();
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
throw new NotImplementedException();
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
throw new NotImplementedException();
}
internal override bool HasCodeAnalysisEmbeddedAttribute => false;
internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Managed;
internal override bool ShouldAddWinRTMembers
{
get { return false; }
}
internal override bool IsWindowsRuntimeImport
{
get
{
return false;
}
}
internal override bool IsComImport
{
get { return false; }
}
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
internal override TypeLayout Layout
{
get { return default(TypeLayout); }
}
internal override System.Runtime.InteropServices.CharSet MarshallingCharSet
{
get { return DefaultMarshallingCharSet; }
}
public override bool IsSerializable
{
get { return false; }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
return null;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override AttributeUsageInfo GetAttributeUsageInfo()
{
return AttributeUsageInfo.Null;
}
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
internal override bool IsRecord => false;
internal override bool IsRecordStruct => false;
internal override bool HasPossibleWellKnownCloneMethod() => false;
internal override bool IsInterpolatedStringHandlerType => false;
internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>();
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptInlineRenameReplacementInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptInlineRenameReplacementInfo
{
/// <summary>
/// The solution obtained after resolving all conflicts.
/// </summary>
Solution NewSolution { get; }
/// <summary>
/// Whether or not the replacement text entered by the user is valid.
/// </summary>
bool ReplacementTextValid { get; }
/// <summary>
/// The documents that need to be updated.
/// </summary>
IEnumerable<DocumentId> DocumentIds { get; }
/// <summary>
/// Returns all the replacements that need to be performed for the specified document.
/// </summary>
IEnumerable<VSTypeScriptInlineRenameReplacementWrapper> GetReplacements(DocumentId documentId);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptInlineRenameReplacementInfo
{
/// <summary>
/// The solution obtained after resolving all conflicts.
/// </summary>
Solution NewSolution { get; }
/// <summary>
/// Whether or not the replacement text entered by the user is valid.
/// </summary>
bool ReplacementTextValid { get; }
/// <summary>
/// The documents that need to be updated.
/// </summary>
IEnumerable<DocumentId> DocumentIds { get; }
/// <summary>
/// Returns all the replacements that need to be performed for the specified document.
/// </summary>
IEnumerable<VSTypeScriptInlineRenameReplacementWrapper> GetReplacements(DocumentId documentId);
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Emit/EditAndContinue/EncVariableSlotAllocator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal sealed class EncVariableSlotAllocator : VariableSlotAllocator
{
// symbols:
private readonly SymbolMatcher _symbolMap;
// syntax:
private readonly Func<SyntaxNode, SyntaxNode?>? _syntaxMap;
private readonly IMethodSymbolInternal _previousTopLevelMethod;
private readonly DebugId _methodId;
// locals:
private readonly IReadOnlyDictionary<EncLocalInfo, int> _previousLocalSlots;
private readonly ImmutableArray<EncLocalInfo> _previousLocals;
// previous state machine:
private readonly string? _stateMachineTypeName;
private readonly int _hoistedLocalSlotCount;
private readonly IReadOnlyDictionary<EncHoistedLocalInfo, int>? _hoistedLocalSlots;
private readonly int _awaiterCount;
private readonly IReadOnlyDictionary<Cci.ITypeReference, int>? _awaiterMap;
// closures:
private readonly IReadOnlyDictionary<int, KeyValuePair<DebugId, int>>? _lambdaMap; // SyntaxOffset -> (Lambda Id, Closure Ordinal)
private readonly IReadOnlyDictionary<int, DebugId>? _closureMap; // SyntaxOffset -> Id
private readonly LambdaSyntaxFacts _lambdaSyntaxFacts;
public EncVariableSlotAllocator(
SymbolMatcher symbolMap,
Func<SyntaxNode, SyntaxNode?>? syntaxMap,
IMethodSymbolInternal previousTopLevelMethod,
DebugId methodId,
ImmutableArray<EncLocalInfo> previousLocals,
IReadOnlyDictionary<int, KeyValuePair<DebugId, int>>? lambdaMap,
IReadOnlyDictionary<int, DebugId>? closureMap,
string? stateMachineTypeName,
int hoistedLocalSlotCount,
IReadOnlyDictionary<EncHoistedLocalInfo, int>? hoistedLocalSlots,
int awaiterCount,
IReadOnlyDictionary<Cci.ITypeReference, int>? awaiterMap,
LambdaSyntaxFacts lambdaSyntaxFacts)
{
Debug.Assert(!previousLocals.IsDefault);
_symbolMap = symbolMap;
_syntaxMap = syntaxMap;
_previousLocals = previousLocals;
_previousTopLevelMethod = previousTopLevelMethod;
_methodId = methodId;
_hoistedLocalSlots = hoistedLocalSlots;
_hoistedLocalSlotCount = hoistedLocalSlotCount;
_stateMachineTypeName = stateMachineTypeName;
_awaiterCount = awaiterCount;
_awaiterMap = awaiterMap;
_lambdaMap = lambdaMap;
_closureMap = closureMap;
_lambdaSyntaxFacts = lambdaSyntaxFacts;
// Create a map from local info to slot.
var previousLocalInfoToSlot = new Dictionary<EncLocalInfo, int>();
for (int slot = 0; slot < previousLocals.Length; slot++)
{
var localInfo = previousLocals[slot];
Debug.Assert(!localInfo.IsDefault);
if (localInfo.IsUnused)
{
// Unrecognized or deleted local.
continue;
}
previousLocalInfoToSlot.Add(localInfo, slot);
}
_previousLocalSlots = previousLocalInfoToSlot;
}
public override DebugId? MethodId => _methodId;
private int CalculateSyntaxOffsetInPreviousMethod(SyntaxNode node)
{
// Note that syntax offset of a syntax node contained in a lambda body is calculated by the containing top-level method,
// not by the lambda method. The offset is thus relative to the top-level method body start. We can thus avoid mapping
// the current lambda symbol or body to the corresponding previous lambda symbol or body, which is non-trivial.
return _previousTopLevelMethod.CalculateLocalSyntaxOffset(_lambdaSyntaxFacts.GetDeclaratorPosition(node), node.SyntaxTree);
}
public override void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder)
{
builder.AddRange(_previousLocals.Select((info, index) =>
{
RoslynDebug.AssertNotNull(info.Signature);
return new SignatureOnlyLocalDefinition(info.Signature, index);
}));
}
private bool TryGetPreviousLocalId(SyntaxNode currentDeclarator, LocalDebugId currentId, out LocalDebugId previousId)
{
if (_syntaxMap == null)
{
// no syntax map
// => the source of the current method is the same as the source of the previous method
// => relative positions are the same
// => synthesized ids are the same
previousId = currentId;
return true;
}
SyntaxNode? previousDeclarator = _syntaxMap(currentDeclarator);
if (previousDeclarator == null)
{
previousId = default;
return false;
}
int syntaxOffset = CalculateSyntaxOffsetInPreviousMethod(previousDeclarator);
previousId = new LocalDebugId(syntaxOffset, currentId.Ordinal);
return true;
}
public override LocalDefinition? GetPreviousLocal(
Cci.ITypeReference currentType,
ILocalSymbolInternal currentLocalSymbol,
string? name,
SynthesizedLocalKind kind,
LocalDebugId id,
LocalVariableAttributes pdbAttributes,
LocalSlotConstraints constraints,
ImmutableArray<bool> dynamicTransformFlags,
ImmutableArray<string> tupleElementNames)
{
if (id.IsNone)
{
return null;
}
if (!TryGetPreviousLocalId(currentLocalSymbol.GetDeclaratorSyntax(), id, out LocalDebugId previousId))
{
return null;
}
var previousType = _symbolMap.MapReference(currentType);
if (previousType == null)
{
return null;
}
// TODO (bug #781309): Should report a warning if the type of the local has changed
// and the previous value will be dropped.
var localKey = new EncLocalInfo(new LocalSlotDebugInfo(kind, previousId), previousType, constraints, signature: null);
if (!_previousLocalSlots.TryGetValue(localKey, out int slot))
{
return null;
}
return new LocalDefinition(
currentLocalSymbol,
name,
currentType,
slot,
kind,
id,
pdbAttributes,
constraints,
dynamicTransformFlags,
tupleElementNames);
}
public override string? PreviousStateMachineTypeName => _stateMachineTypeName;
public override bool TryGetPreviousHoistedLocalSlotIndex(
SyntaxNode currentDeclarator,
Cci.ITypeReference currentType,
SynthesizedLocalKind synthesizedKind,
LocalDebugId currentId,
DiagnosticBag diagnostics,
out int slotIndex)
{
// The previous method was not a state machine (it is allowed to change non-state machine to a state machine):
if (_hoistedLocalSlots == null)
{
slotIndex = -1;
return false;
}
if (!TryGetPreviousLocalId(currentDeclarator, currentId, out LocalDebugId previousId))
{
slotIndex = -1;
return false;
}
var previousType = _symbolMap.MapReference(currentType);
if (previousType == null)
{
slotIndex = -1;
return false;
}
// TODO (bug #781309): Should report a warning if the type of the local has changed
// and the previous value will be dropped.
var localKey = new EncHoistedLocalInfo(new LocalSlotDebugInfo(synthesizedKind, previousId), previousType);
return _hoistedLocalSlots.TryGetValue(localKey, out slotIndex);
}
public override int PreviousHoistedLocalSlotCount => _hoistedLocalSlotCount;
public override int PreviousAwaiterSlotCount => _awaiterCount;
public override bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, DiagnosticBag diagnostics, out int slotIndex)
{
// The previous method was not a state machine (it is allowed to change non-state machine to a state machine):
if (_awaiterMap == null)
{
slotIndex = -1;
return false;
}
var typeRef = _symbolMap.MapReference(currentType);
RoslynDebug.AssertNotNull(typeRef);
return _awaiterMap.TryGetValue(typeRef, out slotIndex);
}
private bool TryGetPreviousSyntaxOffset(SyntaxNode currentSyntax, out int previousSyntaxOffset)
{
// no syntax map
// => the source of the current method is the same as the source of the previous method
// => relative positions are the same
// => ids are the same
SyntaxNode? previousSyntax = _syntaxMap?.Invoke(currentSyntax);
if (previousSyntax == null)
{
previousSyntaxOffset = 0;
return false;
}
previousSyntaxOffset = CalculateSyntaxOffsetInPreviousMethod(previousSyntax);
return true;
}
private bool TryGetPreviousLambdaSyntaxOffset(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out int previousSyntaxOffset)
{
// Syntax map contains mapping for lambdas, but not their bodies.
// Map the lambda first and then determine the corresponding body.
var currentLambdaSyntax = isLambdaBody
? _lambdaSyntaxFacts.GetLambda(lambdaOrLambdaBodySyntax)
: lambdaOrLambdaBodySyntax;
// no syntax map
// => the source of the current method is the same as the source of the previous method
// => relative positions are the same
// => ids are the same
SyntaxNode? previousLambdaSyntax = _syntaxMap?.Invoke(currentLambdaSyntax);
if (previousLambdaSyntax == null)
{
previousSyntaxOffset = 0;
return false;
}
SyntaxNode? previousSyntax;
if (isLambdaBody)
{
previousSyntax = _lambdaSyntaxFacts.TryGetCorrespondingLambdaBody(previousLambdaSyntax, lambdaOrLambdaBodySyntax);
if (previousSyntax == null)
{
previousSyntaxOffset = 0;
return false;
}
}
else
{
previousSyntax = previousLambdaSyntax;
}
previousSyntaxOffset = CalculateSyntaxOffsetInPreviousMethod(previousSyntax);
return true;
}
public override bool TryGetPreviousClosure(SyntaxNode scopeSyntax, out DebugId closureId)
{
if (_closureMap != null &&
TryGetPreviousSyntaxOffset(scopeSyntax, out int syntaxOffset) &&
_closureMap.TryGetValue(syntaxOffset, out closureId))
{
return true;
}
closureId = default;
return false;
}
public override bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId)
{
if (_lambdaMap != null &&
TryGetPreviousLambdaSyntaxOffset(lambdaOrLambdaBodySyntax, isLambdaBody, out int syntaxOffset) &&
_lambdaMap.TryGetValue(syntaxOffset, out var idAndClosureOrdinal))
{
lambdaId = idAndClosureOrdinal.Key;
return true;
}
lambdaId = default;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal sealed class EncVariableSlotAllocator : VariableSlotAllocator
{
// symbols:
private readonly SymbolMatcher _symbolMap;
// syntax:
private readonly Func<SyntaxNode, SyntaxNode?>? _syntaxMap;
private readonly IMethodSymbolInternal _previousTopLevelMethod;
private readonly DebugId _methodId;
// locals:
private readonly IReadOnlyDictionary<EncLocalInfo, int> _previousLocalSlots;
private readonly ImmutableArray<EncLocalInfo> _previousLocals;
// previous state machine:
private readonly string? _stateMachineTypeName;
private readonly int _hoistedLocalSlotCount;
private readonly IReadOnlyDictionary<EncHoistedLocalInfo, int>? _hoistedLocalSlots;
private readonly int _awaiterCount;
private readonly IReadOnlyDictionary<Cci.ITypeReference, int>? _awaiterMap;
// closures:
private readonly IReadOnlyDictionary<int, KeyValuePair<DebugId, int>>? _lambdaMap; // SyntaxOffset -> (Lambda Id, Closure Ordinal)
private readonly IReadOnlyDictionary<int, DebugId>? _closureMap; // SyntaxOffset -> Id
private readonly LambdaSyntaxFacts _lambdaSyntaxFacts;
public EncVariableSlotAllocator(
SymbolMatcher symbolMap,
Func<SyntaxNode, SyntaxNode?>? syntaxMap,
IMethodSymbolInternal previousTopLevelMethod,
DebugId methodId,
ImmutableArray<EncLocalInfo> previousLocals,
IReadOnlyDictionary<int, KeyValuePair<DebugId, int>>? lambdaMap,
IReadOnlyDictionary<int, DebugId>? closureMap,
string? stateMachineTypeName,
int hoistedLocalSlotCount,
IReadOnlyDictionary<EncHoistedLocalInfo, int>? hoistedLocalSlots,
int awaiterCount,
IReadOnlyDictionary<Cci.ITypeReference, int>? awaiterMap,
LambdaSyntaxFacts lambdaSyntaxFacts)
{
Debug.Assert(!previousLocals.IsDefault);
_symbolMap = symbolMap;
_syntaxMap = syntaxMap;
_previousLocals = previousLocals;
_previousTopLevelMethod = previousTopLevelMethod;
_methodId = methodId;
_hoistedLocalSlots = hoistedLocalSlots;
_hoistedLocalSlotCount = hoistedLocalSlotCount;
_stateMachineTypeName = stateMachineTypeName;
_awaiterCount = awaiterCount;
_awaiterMap = awaiterMap;
_lambdaMap = lambdaMap;
_closureMap = closureMap;
_lambdaSyntaxFacts = lambdaSyntaxFacts;
// Create a map from local info to slot.
var previousLocalInfoToSlot = new Dictionary<EncLocalInfo, int>();
for (int slot = 0; slot < previousLocals.Length; slot++)
{
var localInfo = previousLocals[slot];
Debug.Assert(!localInfo.IsDefault);
if (localInfo.IsUnused)
{
// Unrecognized or deleted local.
continue;
}
previousLocalInfoToSlot.Add(localInfo, slot);
}
_previousLocalSlots = previousLocalInfoToSlot;
}
public override DebugId? MethodId => _methodId;
private int CalculateSyntaxOffsetInPreviousMethod(SyntaxNode node)
{
// Note that syntax offset of a syntax node contained in a lambda body is calculated by the containing top-level method,
// not by the lambda method. The offset is thus relative to the top-level method body start. We can thus avoid mapping
// the current lambda symbol or body to the corresponding previous lambda symbol or body, which is non-trivial.
return _previousTopLevelMethod.CalculateLocalSyntaxOffset(_lambdaSyntaxFacts.GetDeclaratorPosition(node), node.SyntaxTree);
}
public override void AddPreviousLocals(ArrayBuilder<Cci.ILocalDefinition> builder)
{
builder.AddRange(_previousLocals.Select((info, index) =>
{
RoslynDebug.AssertNotNull(info.Signature);
return new SignatureOnlyLocalDefinition(info.Signature, index);
}));
}
private bool TryGetPreviousLocalId(SyntaxNode currentDeclarator, LocalDebugId currentId, out LocalDebugId previousId)
{
if (_syntaxMap == null)
{
// no syntax map
// => the source of the current method is the same as the source of the previous method
// => relative positions are the same
// => synthesized ids are the same
previousId = currentId;
return true;
}
SyntaxNode? previousDeclarator = _syntaxMap(currentDeclarator);
if (previousDeclarator == null)
{
previousId = default;
return false;
}
int syntaxOffset = CalculateSyntaxOffsetInPreviousMethod(previousDeclarator);
previousId = new LocalDebugId(syntaxOffset, currentId.Ordinal);
return true;
}
public override LocalDefinition? GetPreviousLocal(
Cci.ITypeReference currentType,
ILocalSymbolInternal currentLocalSymbol,
string? name,
SynthesizedLocalKind kind,
LocalDebugId id,
LocalVariableAttributes pdbAttributes,
LocalSlotConstraints constraints,
ImmutableArray<bool> dynamicTransformFlags,
ImmutableArray<string> tupleElementNames)
{
if (id.IsNone)
{
return null;
}
if (!TryGetPreviousLocalId(currentLocalSymbol.GetDeclaratorSyntax(), id, out LocalDebugId previousId))
{
return null;
}
var previousType = _symbolMap.MapReference(currentType);
if (previousType == null)
{
return null;
}
// TODO (bug #781309): Should report a warning if the type of the local has changed
// and the previous value will be dropped.
var localKey = new EncLocalInfo(new LocalSlotDebugInfo(kind, previousId), previousType, constraints, signature: null);
if (!_previousLocalSlots.TryGetValue(localKey, out int slot))
{
return null;
}
return new LocalDefinition(
currentLocalSymbol,
name,
currentType,
slot,
kind,
id,
pdbAttributes,
constraints,
dynamicTransformFlags,
tupleElementNames);
}
public override string? PreviousStateMachineTypeName => _stateMachineTypeName;
public override bool TryGetPreviousHoistedLocalSlotIndex(
SyntaxNode currentDeclarator,
Cci.ITypeReference currentType,
SynthesizedLocalKind synthesizedKind,
LocalDebugId currentId,
DiagnosticBag diagnostics,
out int slotIndex)
{
// The previous method was not a state machine (it is allowed to change non-state machine to a state machine):
if (_hoistedLocalSlots == null)
{
slotIndex = -1;
return false;
}
if (!TryGetPreviousLocalId(currentDeclarator, currentId, out LocalDebugId previousId))
{
slotIndex = -1;
return false;
}
var previousType = _symbolMap.MapReference(currentType);
if (previousType == null)
{
slotIndex = -1;
return false;
}
// TODO (bug #781309): Should report a warning if the type of the local has changed
// and the previous value will be dropped.
var localKey = new EncHoistedLocalInfo(new LocalSlotDebugInfo(synthesizedKind, previousId), previousType);
return _hoistedLocalSlots.TryGetValue(localKey, out slotIndex);
}
public override int PreviousHoistedLocalSlotCount => _hoistedLocalSlotCount;
public override int PreviousAwaiterSlotCount => _awaiterCount;
public override bool TryGetPreviousAwaiterSlotIndex(Cci.ITypeReference currentType, DiagnosticBag diagnostics, out int slotIndex)
{
// The previous method was not a state machine (it is allowed to change non-state machine to a state machine):
if (_awaiterMap == null)
{
slotIndex = -1;
return false;
}
var typeRef = _symbolMap.MapReference(currentType);
RoslynDebug.AssertNotNull(typeRef);
return _awaiterMap.TryGetValue(typeRef, out slotIndex);
}
private bool TryGetPreviousSyntaxOffset(SyntaxNode currentSyntax, out int previousSyntaxOffset)
{
// no syntax map
// => the source of the current method is the same as the source of the previous method
// => relative positions are the same
// => ids are the same
SyntaxNode? previousSyntax = _syntaxMap?.Invoke(currentSyntax);
if (previousSyntax == null)
{
previousSyntaxOffset = 0;
return false;
}
previousSyntaxOffset = CalculateSyntaxOffsetInPreviousMethod(previousSyntax);
return true;
}
private bool TryGetPreviousLambdaSyntaxOffset(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out int previousSyntaxOffset)
{
// Syntax map contains mapping for lambdas, but not their bodies.
// Map the lambda first and then determine the corresponding body.
var currentLambdaSyntax = isLambdaBody
? _lambdaSyntaxFacts.GetLambda(lambdaOrLambdaBodySyntax)
: lambdaOrLambdaBodySyntax;
// no syntax map
// => the source of the current method is the same as the source of the previous method
// => relative positions are the same
// => ids are the same
SyntaxNode? previousLambdaSyntax = _syntaxMap?.Invoke(currentLambdaSyntax);
if (previousLambdaSyntax == null)
{
previousSyntaxOffset = 0;
return false;
}
SyntaxNode? previousSyntax;
if (isLambdaBody)
{
previousSyntax = _lambdaSyntaxFacts.TryGetCorrespondingLambdaBody(previousLambdaSyntax, lambdaOrLambdaBodySyntax);
if (previousSyntax == null)
{
previousSyntaxOffset = 0;
return false;
}
}
else
{
previousSyntax = previousLambdaSyntax;
}
previousSyntaxOffset = CalculateSyntaxOffsetInPreviousMethod(previousSyntax);
return true;
}
public override bool TryGetPreviousClosure(SyntaxNode scopeSyntax, out DebugId closureId)
{
if (_closureMap != null &&
TryGetPreviousSyntaxOffset(scopeSyntax, out int syntaxOffset) &&
_closureMap.TryGetValue(syntaxOffset, out closureId))
{
return true;
}
closureId = default;
return false;
}
public override bool TryGetPreviousLambda(SyntaxNode lambdaOrLambdaBodySyntax, bool isLambdaBody, out DebugId lambdaId)
{
if (_lambdaMap != null &&
TryGetPreviousLambdaSyntaxOffset(lambdaOrLambdaBodySyntax, isLambdaBody, out int syntaxOffset) &&
_lambdaMap.TryGetValue(syntaxOffset, out var idAndClosureOrdinal))
{
lambdaId = idAndClosureOrdinal.Key;
return true;
}
lambdaId = default;
return false;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/BlockSyntaxExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class BlockSyntaxExtensions
{
public static bool TryConvertToExpressionBody(
this BlockSyntax block,
ParseOptions options, ExpressionBodyPreference preference,
out ExpressionSyntax expression,
out SyntaxToken semicolonToken)
{
if (preference != ExpressionBodyPreference.Never &&
block != null && block.Statements.Count == 1)
{
var firstStatement = block.Statements[0];
var version = ((CSharpParseOptions)options).LanguageVersion;
if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) &&
MatchesPreference(expression, preference))
{
// The close brace of the block may have important trivia on it (like
// comments or directives). Preserve them on the semicolon when we
// convert to an expression body.
semicolonToken = semicolonToken.WithAppendedTrailingTrivia(
block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine()));
return true;
}
}
expression = null;
semicolonToken = default;
return false;
}
public static bool TryConvertToArrowExpressionBody(
this BlockSyntax block, SyntaxKind declarationKind,
ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression,
out SyntaxToken semicolonToken)
{
var version = ((CSharpParseOptions)options).LanguageVersion;
// We can always use arrow-expression bodies in C# 7 or above.
// We can also use them in C# 6, but only a select set of member kinds.
var acceptableVersion =
version >= LanguageVersion.CSharp7 ||
(version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind));
if (!acceptableVersion ||
!block.TryConvertToExpressionBody(
options, preference,
out var expression, out semicolonToken))
{
arrowExpression = null;
semicolonToken = default;
return false;
}
arrowExpression = SyntaxFactory.ArrowExpressionClause(expression);
return true;
}
private static bool IsSupportedInCSharp6(SyntaxKind declarationKind)
{
switch (declarationKind)
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
return false;
}
return true;
}
public static bool MatchesPreference(
ExpressionSyntax expression, ExpressionBodyPreference preference)
{
if (preference == ExpressionBodyPreference.WhenPossible)
{
return true;
}
Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine);
return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false);
}
private static bool TryGetExpression(
LanguageVersion version, StatementSyntax firstStatement,
out ExpressionSyntax expression, out SyntaxToken semicolonToken)
{
if (firstStatement is ExpressionStatementSyntax exprStatement)
{
expression = exprStatement.Expression;
semicolonToken = exprStatement.SemicolonToken;
return true;
}
else if (firstStatement is ReturnStatementSyntax returnStatement)
{
if (returnStatement.Expression != null)
{
// If there are any comments or directives on the return keyword, move them to
// the expression.
expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment())
? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia())
: returnStatement.Expression;
semicolonToken = returnStatement.SemicolonToken;
return true;
}
}
else if (firstStatement is ThrowStatementSyntax throwStatement)
{
if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null)
{
expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression);
semicolonToken = throwStatement.SemicolonToken;
return true;
}
}
expression = null;
semicolonToken = default;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class BlockSyntaxExtensions
{
public static bool TryConvertToExpressionBody(
this BlockSyntax block,
ParseOptions options, ExpressionBodyPreference preference,
out ExpressionSyntax expression,
out SyntaxToken semicolonToken)
{
if (preference != ExpressionBodyPreference.Never &&
block != null && block.Statements.Count == 1)
{
var firstStatement = block.Statements[0];
var version = ((CSharpParseOptions)options).LanguageVersion;
if (TryGetExpression(version, firstStatement, out expression, out semicolonToken) &&
MatchesPreference(expression, preference))
{
// The close brace of the block may have important trivia on it (like
// comments or directives). Preserve them on the semicolon when we
// convert to an expression body.
semicolonToken = semicolonToken.WithAppendedTrailingTrivia(
block.CloseBraceToken.LeadingTrivia.Where(t => !t.IsWhitespaceOrEndOfLine()));
return true;
}
}
expression = null;
semicolonToken = default;
return false;
}
public static bool TryConvertToArrowExpressionBody(
this BlockSyntax block, SyntaxKind declarationKind,
ParseOptions options, ExpressionBodyPreference preference,
out ArrowExpressionClauseSyntax arrowExpression,
out SyntaxToken semicolonToken)
{
var version = ((CSharpParseOptions)options).LanguageVersion;
// We can always use arrow-expression bodies in C# 7 or above.
// We can also use them in C# 6, but only a select set of member kinds.
var acceptableVersion =
version >= LanguageVersion.CSharp7 ||
(version >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind));
if (!acceptableVersion ||
!block.TryConvertToExpressionBody(
options, preference,
out var expression, out semicolonToken))
{
arrowExpression = null;
semicolonToken = default;
return false;
}
arrowExpression = SyntaxFactory.ArrowExpressionClause(expression);
return true;
}
private static bool IsSupportedInCSharp6(SyntaxKind declarationKind)
{
switch (declarationKind)
{
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
return false;
}
return true;
}
public static bool MatchesPreference(
ExpressionSyntax expression, ExpressionBodyPreference preference)
{
if (preference == ExpressionBodyPreference.WhenPossible)
{
return true;
}
Contract.ThrowIfFalse(preference == ExpressionBodyPreference.WhenOnSingleLine);
return CSharpSyntaxFacts.Instance.IsOnSingleLine(expression, fullSpan: false);
}
private static bool TryGetExpression(
LanguageVersion version, StatementSyntax firstStatement,
out ExpressionSyntax expression, out SyntaxToken semicolonToken)
{
if (firstStatement is ExpressionStatementSyntax exprStatement)
{
expression = exprStatement.Expression;
semicolonToken = exprStatement.SemicolonToken;
return true;
}
else if (firstStatement is ReturnStatementSyntax returnStatement)
{
if (returnStatement.Expression != null)
{
// If there are any comments or directives on the return keyword, move them to
// the expression.
expression = firstStatement.GetLeadingTrivia().Any(t => t.IsDirective || t.IsSingleOrMultiLineComment())
? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia())
: returnStatement.Expression;
semicolonToken = returnStatement.SemicolonToken;
return true;
}
}
else if (firstStatement is ThrowStatementSyntax throwStatement)
{
if (version >= LanguageVersion.CSharp7 && throwStatement.Expression != null)
{
expression = SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression);
semicolonToken = throwStatement.SemicolonToken;
return true;
}
}
expression = null;
semicolonToken = default;
return false;
}
}
}
| -1 |
dotnet/roslyn | 54,966 | Fix 'line separators' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T01:21:43Z | 2021-07-20T07:17:27Z | 21d77e7a48ec8b7556b708d64cb5a63e88f3a255 | 28191eef78568088a332a435dcd734fad1bd4fbf | Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/CommandLine/AnalyzerConfig.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a single EditorConfig file, see https://editorconfig.org for details about the format.
/// </summary>
public sealed partial class AnalyzerConfig
{
// Matches EditorConfig section header such as "[*.{js,py}]", see https://editorconfig.org for details
private static readonly Regex s_sectionMatcher = new Regex(@"^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$", RegexOptions.Compiled);
// Matches EditorConfig property such as "indent_style = space", see https://editorconfig.org for details
private static readonly Regex s_propertyMatcher = new Regex(@"^\s*([\w\.\-_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$", RegexOptions.Compiled);
/// <summary>
/// Key that indicates if this config is a global config
/// </summary>
internal const string GlobalKey = "is_global";
/// <summary>
/// Key that indicates the precedence of this config when <see cref="IsGlobal"/> is true
/// </summary>
internal const string GlobalLevelKey = "global_level";
/// <summary>
/// Filename that indicates this file is a user provided global config
/// </summary>
internal const string UserGlobalConfigName = ".globalconfig";
/// <summary>
/// A set of keys that are reserved for special interpretation for the editorconfig specification.
/// All values corresponding to reserved keys in a (key,value) property pair are always lowercased
/// during parsing.
/// </summary>
/// <remarks>
/// This list was retrieved from https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties
/// at 2018-04-21 19:37:05Z. New keys may be added to this list in newer versions, but old ones will
/// not be removed.
/// </remarks>
internal static ImmutableHashSet<string> ReservedKeys { get; }
= ImmutableHashSet.CreateRange(Section.PropertiesKeyComparer, new[] {
"root",
"indent_style",
"indent_size",
"tab_width",
"end_of_line",
"charset",
"trim_trailing_whitespace",
"insert_final_newline",
});
/// <summary>
/// A set of values that are reserved for special use for the editorconfig specification
/// and will always be lower-cased by the parser.
/// </summary>
internal static ImmutableHashSet<string> ReservedValues { get; }
= ImmutableHashSet.CreateRange(CaseInsensitiveComparison.Comparer, new[] { "unset" });
internal Section GlobalSection { get; }
/// <summary>
/// The directory the editorconfig was contained in, with all directory separators
/// replaced with '/'.
/// </summary>
internal string NormalizedDirectory { get; }
/// <summary>
/// The path passed to <see cref="Parse(string, string)"/> during construction.
/// </summary>
internal string PathToFile { get; }
/// <summary>
/// Comparer for sorting <see cref="AnalyzerConfig"/> files by <see cref="NormalizedDirectory"/> path length.
/// </summary>
internal static Comparer<AnalyzerConfig> DirectoryLengthComparer { get; } = Comparer<AnalyzerConfig>.Create(
(e1, e2) => e1.NormalizedDirectory.Length.CompareTo(e2.NormalizedDirectory.Length));
internal ImmutableArray<Section> NamedSections { get; }
/// <summary>
/// Gets whether this editorconfig is a topmost editorconfig.
/// </summary>
internal bool IsRoot => GlobalSection.Properties.TryGetValue("root", out string? val) && val == "true";
/// <summary>
/// Gets whether this editorconfig is a global editorconfig.
/// </summary>
internal bool IsGlobal => _hasGlobalFileName || GlobalSection.Properties.ContainsKey(GlobalKey);
/// <summary>
/// Get the global level of this config, used to resolve conflicting keys
/// </summary>
/// <remarks>
/// A user can explicitly set the global level via the <see cref="GlobalLevelKey"/>.
/// When no global level is explicitly set, we use a heuristic:
/// <list type="bullet">
/// <item><description>
/// Any file matching the <see cref="UserGlobalConfigName"/> is determined to be a user supplied global config and gets a level of 100
/// </description></item>
/// <item><description>
/// Any other file gets a default level of 0
/// </description></item>
/// </list>
///
/// This value is unused when <see cref="IsGlobal"/> is <c>false</c>.
/// </remarks>
internal int GlobalLevel
{
get
{
if (GlobalSection.Properties.TryGetValue(GlobalLevelKey, out string? val) && int.TryParse(val, out int level))
{
return level;
}
else if (_hasGlobalFileName)
{
return 100;
}
else
{
return 0;
}
}
}
private readonly bool _hasGlobalFileName;
private AnalyzerConfig(
Section globalSection,
ImmutableArray<Section> namedSections,
string pathToFile)
{
GlobalSection = globalSection;
NamedSections = namedSections;
PathToFile = pathToFile;
_hasGlobalFileName = Path.GetFileName(pathToFile).Equals(UserGlobalConfigName, StringComparison.OrdinalIgnoreCase);
// Find the containing directory and normalize the path separators
string directory = Path.GetDirectoryName(pathToFile) ?? pathToFile;
NormalizedDirectory = PathUtilities.NormalizeWithForwardSlash(directory);
}
/// <summary>
/// Parses an editor config file text located at the given path. No parsing
/// errors are reported. If any line contains a parse error, it is dropped.
/// </summary>
public static AnalyzerConfig Parse(string text, string? pathToFile)
{
return Parse(SourceText.From(text), pathToFile);
}
/// <summary>
/// Parses an editor config file text located at the given path. No parsing
/// errors are reported. If any line contains a parse error, it is dropped.
/// </summary>
public static AnalyzerConfig Parse(SourceText text, string? pathToFile)
{
if (pathToFile is null || !Path.IsPathRooted(pathToFile) || string.IsNullOrEmpty(Path.GetFileName(pathToFile)))
{
throw new ArgumentException("Must be an absolute path to an editorconfig file", nameof(pathToFile));
}
Section? globalSection = null;
var namedSectionBuilder = ImmutableArray.CreateBuilder<Section>();
// N.B. The editorconfig documentation is quite loose on property interpretation.
// Specifically, it says:
// Currently all properties and values are case-insensitive.
// They are lowercased when parsed.
// To accommodate this, we use a lower case Unicode mapping when adding to the
// dictionary, but we also use a case-insensitive key comparer when doing lookups
var activeSectionProperties = ImmutableDictionary.CreateBuilder<string, string>(
Section.PropertiesKeyComparer);
string activeSectionName = "";
foreach (var textLine in text.Lines)
{
string line = textLine.ToString();
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
if (IsComment(line))
{
continue;
}
var sectionMatches = s_sectionMatcher.Matches(line);
if (sectionMatches.Count > 0 && sectionMatches[0].Groups.Count > 0)
{
addNewSection();
var sectionName = sectionMatches[0].Groups[1].Value;
Debug.Assert(!string.IsNullOrEmpty(sectionName));
activeSectionName = sectionName;
activeSectionProperties = ImmutableDictionary.CreateBuilder<string, string>(
Section.PropertiesKeyComparer);
continue;
}
var propMatches = s_propertyMatcher.Matches(line);
if (propMatches.Count > 0 && propMatches[0].Groups.Count > 1)
{
var key = propMatches[0].Groups[1].Value;
var value = propMatches[0].Groups[2].Value;
Debug.Assert(!string.IsNullOrEmpty(key));
Debug.Assert(key == key.Trim());
Debug.Assert(value == value?.Trim());
key = CaseInsensitiveComparison.ToLower(key);
if (ReservedKeys.Contains(key) || ReservedValues.Contains(value))
{
value = CaseInsensitiveComparison.ToLower(value);
}
activeSectionProperties[key] = value ?? "";
continue;
}
}
// Add the last section
addNewSection();
return new AnalyzerConfig(globalSection!, namedSectionBuilder.ToImmutable(), pathToFile);
void addNewSection()
{
// Close out the previous section
var previousSection = new Section(activeSectionName, activeSectionProperties.ToImmutable());
if (activeSectionName == "")
{
// This is the global section
globalSection = previousSection;
}
else
{
namedSectionBuilder.Add(previousSection);
}
}
}
private static bool IsComment(string line)
{
foreach (char c in line)
{
if (!char.IsWhiteSpace(c))
{
return c == '#' || c == ';';
}
}
return false;
}
/// <summary>
/// Represents a named section of the editorconfig file, which consists of a name followed by a set
/// of key-value pairs.
/// </summary>
internal sealed class Section
{
/// <summary>
/// Used to compare <see cref="Name"/>s of sections. Specified by editorconfig to
/// be a case-sensitive comparison.
/// </summary>
public static StringComparison NameComparer { get; } = StringComparison.Ordinal;
/// <summary>
/// Used to compare <see cref="Name"/>s of sections. Specified by editorconfig to
/// be a case-sensitive comparison.
/// </summary>
public static IEqualityComparer<string> NameEqualityComparer { get; } = StringComparer.Ordinal;
/// <summary>
/// Used to compare keys in <see cref="Properties"/>. The editorconfig spec defines property
/// keys as being compared case-insensitively according to Unicode lower-case rules.
/// </summary>
public static StringComparer PropertiesKeyComparer { get; } = CaseInsensitiveComparison.Comparer;
public Section(string name, ImmutableDictionary<string, string> properties)
{
Name = name;
Properties = properties;
}
/// <summary>
/// The name as present directly in the section specification of the editorconfig file.
/// </summary>
public string Name { get; }
/// <summary>
/// Keys and values for this section. All keys are lower-cased according to the
/// EditorConfig specification and keys are compared case-insensitively. Values are
/// lower-cased if the value appears in <see cref="ReservedValues" />
/// or if the corresponding key is in <see cref="ReservedKeys" />. Otherwise,
/// the values are the literal values present in the source.
/// </summary>
public ImmutableDictionary<string, string> Properties { get; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a single EditorConfig file, see https://editorconfig.org for details about the format.
/// </summary>
public sealed partial class AnalyzerConfig
{
// Matches EditorConfig section header such as "[*.{js,py}]", see https://editorconfig.org for details
private static readonly Regex s_sectionMatcher = new Regex(@"^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$", RegexOptions.Compiled);
// Matches EditorConfig property such as "indent_style = space", see https://editorconfig.org for details
private static readonly Regex s_propertyMatcher = new Regex(@"^\s*([\w\.\-_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$", RegexOptions.Compiled);
/// <summary>
/// Key that indicates if this config is a global config
/// </summary>
internal const string GlobalKey = "is_global";
/// <summary>
/// Key that indicates the precedence of this config when <see cref="IsGlobal"/> is true
/// </summary>
internal const string GlobalLevelKey = "global_level";
/// <summary>
/// Filename that indicates this file is a user provided global config
/// </summary>
internal const string UserGlobalConfigName = ".globalconfig";
/// <summary>
/// A set of keys that are reserved for special interpretation for the editorconfig specification.
/// All values corresponding to reserved keys in a (key,value) property pair are always lowercased
/// during parsing.
/// </summary>
/// <remarks>
/// This list was retrieved from https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties
/// at 2018-04-21 19:37:05Z. New keys may be added to this list in newer versions, but old ones will
/// not be removed.
/// </remarks>
internal static ImmutableHashSet<string> ReservedKeys { get; }
= ImmutableHashSet.CreateRange(Section.PropertiesKeyComparer, new[] {
"root",
"indent_style",
"indent_size",
"tab_width",
"end_of_line",
"charset",
"trim_trailing_whitespace",
"insert_final_newline",
});
/// <summary>
/// A set of values that are reserved for special use for the editorconfig specification
/// and will always be lower-cased by the parser.
/// </summary>
internal static ImmutableHashSet<string> ReservedValues { get; }
= ImmutableHashSet.CreateRange(CaseInsensitiveComparison.Comparer, new[] { "unset" });
internal Section GlobalSection { get; }
/// <summary>
/// The directory the editorconfig was contained in, with all directory separators
/// replaced with '/'.
/// </summary>
internal string NormalizedDirectory { get; }
/// <summary>
/// The path passed to <see cref="Parse(string, string)"/> during construction.
/// </summary>
internal string PathToFile { get; }
/// <summary>
/// Comparer for sorting <see cref="AnalyzerConfig"/> files by <see cref="NormalizedDirectory"/> path length.
/// </summary>
internal static Comparer<AnalyzerConfig> DirectoryLengthComparer { get; } = Comparer<AnalyzerConfig>.Create(
(e1, e2) => e1.NormalizedDirectory.Length.CompareTo(e2.NormalizedDirectory.Length));
internal ImmutableArray<Section> NamedSections { get; }
/// <summary>
/// Gets whether this editorconfig is a topmost editorconfig.
/// </summary>
internal bool IsRoot => GlobalSection.Properties.TryGetValue("root", out string? val) && val == "true";
/// <summary>
/// Gets whether this editorconfig is a global editorconfig.
/// </summary>
internal bool IsGlobal => _hasGlobalFileName || GlobalSection.Properties.ContainsKey(GlobalKey);
/// <summary>
/// Get the global level of this config, used to resolve conflicting keys
/// </summary>
/// <remarks>
/// A user can explicitly set the global level via the <see cref="GlobalLevelKey"/>.
/// When no global level is explicitly set, we use a heuristic:
/// <list type="bullet">
/// <item><description>
/// Any file matching the <see cref="UserGlobalConfigName"/> is determined to be a user supplied global config and gets a level of 100
/// </description></item>
/// <item><description>
/// Any other file gets a default level of 0
/// </description></item>
/// </list>
///
/// This value is unused when <see cref="IsGlobal"/> is <c>false</c>.
/// </remarks>
internal int GlobalLevel
{
get
{
if (GlobalSection.Properties.TryGetValue(GlobalLevelKey, out string? val) && int.TryParse(val, out int level))
{
return level;
}
else if (_hasGlobalFileName)
{
return 100;
}
else
{
return 0;
}
}
}
private readonly bool _hasGlobalFileName;
private AnalyzerConfig(
Section globalSection,
ImmutableArray<Section> namedSections,
string pathToFile)
{
GlobalSection = globalSection;
NamedSections = namedSections;
PathToFile = pathToFile;
_hasGlobalFileName = Path.GetFileName(pathToFile).Equals(UserGlobalConfigName, StringComparison.OrdinalIgnoreCase);
// Find the containing directory and normalize the path separators
string directory = Path.GetDirectoryName(pathToFile) ?? pathToFile;
NormalizedDirectory = PathUtilities.NormalizeWithForwardSlash(directory);
}
/// <summary>
/// Parses an editor config file text located at the given path. No parsing
/// errors are reported. If any line contains a parse error, it is dropped.
/// </summary>
public static AnalyzerConfig Parse(string text, string? pathToFile)
{
return Parse(SourceText.From(text), pathToFile);
}
/// <summary>
/// Parses an editor config file text located at the given path. No parsing
/// errors are reported. If any line contains a parse error, it is dropped.
/// </summary>
public static AnalyzerConfig Parse(SourceText text, string? pathToFile)
{
if (pathToFile is null || !Path.IsPathRooted(pathToFile) || string.IsNullOrEmpty(Path.GetFileName(pathToFile)))
{
throw new ArgumentException("Must be an absolute path to an editorconfig file", nameof(pathToFile));
}
Section? globalSection = null;
var namedSectionBuilder = ImmutableArray.CreateBuilder<Section>();
// N.B. The editorconfig documentation is quite loose on property interpretation.
// Specifically, it says:
// Currently all properties and values are case-insensitive.
// They are lowercased when parsed.
// To accommodate this, we use a lower case Unicode mapping when adding to the
// dictionary, but we also use a case-insensitive key comparer when doing lookups
var activeSectionProperties = ImmutableDictionary.CreateBuilder<string, string>(
Section.PropertiesKeyComparer);
string activeSectionName = "";
foreach (var textLine in text.Lines)
{
string line = textLine.ToString();
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
if (IsComment(line))
{
continue;
}
var sectionMatches = s_sectionMatcher.Matches(line);
if (sectionMatches.Count > 0 && sectionMatches[0].Groups.Count > 0)
{
addNewSection();
var sectionName = sectionMatches[0].Groups[1].Value;
Debug.Assert(!string.IsNullOrEmpty(sectionName));
activeSectionName = sectionName;
activeSectionProperties = ImmutableDictionary.CreateBuilder<string, string>(
Section.PropertiesKeyComparer);
continue;
}
var propMatches = s_propertyMatcher.Matches(line);
if (propMatches.Count > 0 && propMatches[0].Groups.Count > 1)
{
var key = propMatches[0].Groups[1].Value;
var value = propMatches[0].Groups[2].Value;
Debug.Assert(!string.IsNullOrEmpty(key));
Debug.Assert(key == key.Trim());
Debug.Assert(value == value?.Trim());
key = CaseInsensitiveComparison.ToLower(key);
if (ReservedKeys.Contains(key) || ReservedValues.Contains(value))
{
value = CaseInsensitiveComparison.ToLower(value);
}
activeSectionProperties[key] = value ?? "";
continue;
}
}
// Add the last section
addNewSection();
return new AnalyzerConfig(globalSection!, namedSectionBuilder.ToImmutable(), pathToFile);
void addNewSection()
{
// Close out the previous section
var previousSection = new Section(activeSectionName, activeSectionProperties.ToImmutable());
if (activeSectionName == "")
{
// This is the global section
globalSection = previousSection;
}
else
{
namedSectionBuilder.Add(previousSection);
}
}
}
private static bool IsComment(string line)
{
foreach (char c in line)
{
if (!char.IsWhiteSpace(c))
{
return c == '#' || c == ';';
}
}
return false;
}
/// <summary>
/// Represents a named section of the editorconfig file, which consists of a name followed by a set
/// of key-value pairs.
/// </summary>
internal sealed class Section
{
/// <summary>
/// Used to compare <see cref="Name"/>s of sections. Specified by editorconfig to
/// be a case-sensitive comparison.
/// </summary>
public static StringComparison NameComparer { get; } = StringComparison.Ordinal;
/// <summary>
/// Used to compare <see cref="Name"/>s of sections. Specified by editorconfig to
/// be a case-sensitive comparison.
/// </summary>
public static IEqualityComparer<string> NameEqualityComparer { get; } = StringComparer.Ordinal;
/// <summary>
/// Used to compare keys in <see cref="Properties"/>. The editorconfig spec defines property
/// keys as being compared case-insensitively according to Unicode lower-case rules.
/// </summary>
public static StringComparer PropertiesKeyComparer { get; } = CaseInsensitiveComparison.Comparer;
public Section(string name, ImmutableDictionary<string, string> properties)
{
Name = name;
Properties = properties;
}
/// <summary>
/// The name as present directly in the section specification of the editorconfig file.
/// </summary>
public string Name { get; }
/// <summary>
/// Keys and values for this section. All keys are lower-cased according to the
/// EditorConfig specification and keys are compared case-insensitively. Values are
/// lower-cased if the value appears in <see cref="ReservedValues" />
/// or if the corresponding key is in <see cref="ReservedKeys" />. Otherwise,
/// the values are the literal values present in the source.
/// </summary>
public ImmutableDictionary<string, string> Properties { get; }
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.